package c;
/**
* @author : majun
* @date :2014年8月26日下午5:08:21
* @version:v1.0+
* @FileName:Factory.java
* @ProjectName:javatest
* @PackageName:c
* @EnclosingType:
* @Description:静态工厂模式 --
*/
public class Factory {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Factory f = Factory.obtain();
f.setX(i);
System.out.println(f.getX());
}
}
private Factory() {
}
private static final int MAX_POOL_SIZE = 50;
private static int sPoolSize = 0;
private static Object myLock = new Object();
private Factory next;
private static Factory mPool;
private int x =100;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public static Factory obtain() {
synchronized (myLock) {
if (mPool != null) {
Factory factory = mPool;
mPool = factory.next;
factory.next = null;
sPoolSize--;
return factory;
}
}
return new Factory(); // next = null
}
/**
*
*@data :2014年8月26日下午5:31:10
*@description :回收
*/
public void recycle() {
synchronized (myLock) {
if (sPoolSize < MAX_POOL_SIZE) { // 0 < 50
next = mPool;
this.x = 1020;
mPool = this;
sPoolSize++;
}
}
}
}
减少对象创建 内存优化------------------------------------------------------------------>
减少对象创建 内存优化------------------------------------------------------------------>