📄 client.java
字号:
/*
* Created on 2005-5-11
*
意图 运用共享技术有效地支持大量细粒度的对象。
适用性 一个应用程序使用了大量的对象。
完全由于使用大量的对象,造成很大的存储开销。
对象的大多数状态都可变为外部状态。
如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象。
应用程序不依赖于对象标识。由于F l y w e i g h t 对象可以被共享,对于概念上明显有别的对象,标识测试将返回真值。
*/
package com.test.pattern.struct.flyweight;
import java.util.ArrayList;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
class FlyweightFactory {
private ArrayList pool = new ArrayList();
// the flyweightfactory can crete all entries in the pool at startup
// (if the pool is small, and it is likely all will be used), or as
// needed, if the pool si large and it is likely some will never be used
public FlyweightFactory() {
pool.add(new ConcreteEvenFlyweight());
pool.add(new ConcreteUnevenFlyweight());
}
public Flyweight GetFlyweight(int key) {
// here we would determine if the flyweight identified by key
// exists, and if so return it. If not, we would create it.
// As in this demo we have implementation all the possible
// flyweights we wish to use, we retrun the suitable one.
int i = key % 2;
return ((Flyweight) pool.get(i));
}
}
abstract class Flyweight {
abstract public void DoOperation(int extrinsicState);
}
class UnsharedConcreteFlyweight extends Flyweight {
public void DoOperation(int extrinsicState) {
}
}
class ConcreteEvenFlyweight extends Flyweight {
public void DoOperation(int extrinsicState) {
System.out.println("In ConcreteEvenFlyweight.DoOperation: "
+ extrinsicState);
}
}
class ConcreteUnevenFlyweight extends Flyweight {
public void DoOperation(int extrinsicState) {
System.out.println("In ConcreteUnevenFlyweight.DoOperation: "
+ extrinsicState);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client {
public static void main(String[] args) {
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8 };
FlyweightFactory f = new FlyweightFactory();
int extrinsicState = 3;
for (int i = 0; i < data.length; i++) {
Flyweight flyweight = f.GetFlyweight(i);
flyweight.DoOperation(extrinsicState);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -