设计模式学习之享元模式

享元模式:运用共享技术有效地支持大量细粒度的对象。主要用于避免大量非常相似类的开销。在很多程序设计中,有时需要生成大量细粒度的类实例来表示数据,这时候可以采用享元模式来共享这些类实例,从而减少这些实例的数量。

 

代码示例:

享元抽象类:
package DesignPattern.FlyweightPattern;

public abstract class Flyweight {

	public abstract void Operate(int i);
}

 

具体享元类:
package DesignPattern.FlyweightPattern;

public class ConcreateFlyweight extends Flyweight {

	@Override
	public void Operate(int i) {
		// TODO Auto-generated method stub
		System.out.println("具体享元:" + i);
	}
}

 

享元抽象类:
package DesignPattern.FlyweightPattern;

import java.util.Hashtable;

public class FlyweightFactory {

	private Hashtable flyWeights = new Hashtable();
	
	public FlyweightFactory() {
		this.flyWeights.put("A", new ConcreateFlyweight());
		this.flyWeights.put("B", new ConcreateFlyweight());
		this.flyWeights.put("C", new ConcreateFlyweight());
	}
	
	public Flyweight getFlyweight(String key) {
		return (Flyweight) flyWeights.get(key);
	}
}

 

主控程序类:
package DesignPattern.FlyweightPattern;

public class Client {

	public static void main(String[] args) {
		int i = 1;
		FlyweightFactory factory = new FlyweightFactory();
		Flyweight fly1 = factory.getFlyweight("A");
		fly1.Operate(++i);
		Flyweight fly2 = factory.getFlyweight("B");
		fly2.Operate(++i);
		Flyweight fly3 = factory.getFlyweight("C");
		fly3.Operate(++i);
		Flyweight fly4 = factory.getFlyweight("B");
		fly4.Operate(++i);
		Flyweight fly5 = factory.getFlyweight("B");
		fly5.Operate(++i);
		Flyweight fly6 = factory.getFlyweight("B");
		fly6.Operate(++i);
	}
}

  

你可能感兴趣的:(享元模式)