JAVA设计模式(11)结构型-享元模式

享元模式(Flyweight Pattern):以共享的方式高效的支持大量的细粒度对象。通过复用内存中已存在的对象,降低系统创建对象实例的性能消耗。

//@author V:jbossjf

package Chartflyweight;

import java.util.Hashtable;

public class CharactorFactory {
	private Hashtable<String, FlyWeight> charactors = new Hashtable<String, FlyWeight>();

	// 构造函数
	public CharactorFactory() {
		charactors.put("A", new FlyWeightAIml());
		charactors.put("B", new FlyWeightBIml());
	}

	// 获得指定字符实例
	public FlyWeight getCharactor(String key) {
		FlyWeight charactor = (FlyWeight) charactors.get(key);
		if (charactor == null) {
			if (key.equals("A")) {
				charactor = new FlyWeightAIml();
			} else if (key.equals("B")) {
				charactor = new FlyWeightBIml();
			}
			charactors.put(key, charactor);
		}
		return charactor;
	}
}
package Chartflyweight;

public abstract class FlyWeight {
	protected String charStr = "";

	protected int fontSize;

	protected abstract void operator(int fontSize);

	// 显示方法
	protected abstract void displayCharator();

}
package Chartflyweight;

public class FlyWeightAIml extends FlyWeight {


	@Override
	protected void operator(int fontSize) {
       this.fontSize=fontSize;
	}
	
	

	public FlyWeightAIml() {
		this.charStr = "A";
		this.fontSize=12;
	}



	@Override
	protected void displayCharator() {
		System.out.println("字符:" + this.charStr + ",大小:" + fontSize);
	}

}
package Chartflyweight;

public class FlyWeightBIml extends FlyWeight {

	@Override
	protected void operator(int fontSize) {
		this.fontSize = fontSize;
	}

	public FlyWeightBIml() {
		this.charStr = "B";
		this.fontSize = 12;
	}

	@Override
	protected void displayCharator() {
		System.out.println("字符:" + this.charStr + ",大小:" + fontSize);
	}

}
package Chartflyweight;

//如何有特别多的外部状态,则需要很多的函数,函数进行抽取


public class Clinet {
	public static void main(String[] args) {
		FlyWeightAIml a = new FlyWeightAIml();
		FlyWeightBIml b = new FlyWeightBIml();
		// 显示字符A
		display(a, 12);
		// 显示字符B
		display(b, 14);
	}

	// 设置字符的大小
	public static void display(FlyWeight objChar, int nSize) {
		try {
			System.out.println("字符:" + objChar.charStr + ",大小:" + nSize);
		} catch (Exception err) {
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值