大话设计模式之享元模式

享元模式,运用共享技术有效地支持大量细粒度的对象。

大话设计模式之享元模式_第1张图片

package Flyweight;

import java.util.HashMap;

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int extrinsicstate = 22;
		FlyweightFactory f = new FlyweightFactory();
		
		Flyweight fx = f.GetFlyweight("x");
		fx.Operation(--extrinsicstate);
		
		Flyweight fy = f.GetFlyweight("y");
		fy.Operation(--extrinsicstate);
		
		Flyweight fz = f.GetFlyweight("z");
		fz.Operation(--extrinsicstate);
		
		UnsharedConcreteFlyweight uf = new UnsharedConcreteFlyweight();
		
		uf.Operation(--extrinsicstate);
	}

}

abstract class Flyweight {
	public abstract void Operation(int extrinsicstate);
}

class ConcreteFlyweight extends Flyweight {

	@Override
	public void Operation(int extrinsicstate) {
		// TODO Auto-generated method stub
		System.out.println("concreteFlyweight:"+extrinsicstate);
	}
}

class UnsharedConcreteFlyweight extends Flyweight {

	@Override
	public void Operation(int extrinsicstate) {
		// TODO Auto-generated method stub
		System.out.println("UnsharedConcreteFlyweight:"+extrinsicstate);
	}
}

class FlyweightFactory {
	private HashMap<String,Flyweight> flyweights = new HashMap<>();
	public FlyweightFactory() {
		flyweights.put("x", new ConcreteFlyweight());
		flyweights.put("y", new ConcreteFlyweight());
		flyweights.put("z", new ConcreteFlyweight());
	}
	
	public Flyweight GetFlyweight(String key) {
		return flyweights.get(key);
	}
}

如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用;还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。


你可能感兴趣的:(大话设计模式之享元模式)