Java设计模式-----FlyWeight享元模式

本文介绍了享元模式的基本概念及其在程序设计中的应用。通过具体示例展示了如何利用享元模式来减少内存消耗并提高程序效率。享元模式适用于需要创建大量相似对象的场景,能够通过共享对象减轻系统负担。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源自:http://www.blogjava.net/flustar/archive/2008/01/26/flyw.html

FlyWeight享元模式:

运用共享技术有效地支持大量细粒度对象。

也就是说在一个系统中如果有多个相同的对象,那么只共享一份就可以了,不必每个都去实例化一个对象。在Flyweight模式中,由于要产生各种各样的对象,所以在Flyweight(享元)模式中常出现Factory模式。Flyweight的内部状态是用来共享的,Flyweight factory负责维护一个对象存储池(Flyweight Pool)来存放内部状态的对象。Flyweight模式是一个提高程序效率和性能的模式,会大大加快程序的运行速度。

例子:

public abstract class Character {

	protected char symbol;
	protected int width;
	protected int height;
	protected int ascent;
	protected int descent;
	protected int pointSize;

	public abstract void Display(int pointSize);
}

public class CharacterA extends Character {

	public CharacterA() {
		this.symbol = 'A';
		this.height = 100;
		this.width = 120;
		this.ascent = 70;
		this.descent = 0;
	}

	public void Display(int pointSize) {
		this.pointSize = pointSize;
		System.out.println(this.symbol + " (pointsize " + this.pointSize + ")");
	}
}

public class CharacterB extends Character {

	public CharacterB() {
		this.symbol = 'B';
		this.height = 100;
		this.width = 140;
		this.ascent = 72;
		this.descent = 0;
	}

	public void Display(int pointSize) {
		this.pointSize = pointSize;
		System.out.println(this.symbol + " (pointsize " + this.pointSize + ")");
	}
}

//C, D, E, etc.

public class CharacterZ extends Character {

	public CharacterZ() {
		this.symbol = 'Z';
		this.height = 100;
		this.width = 100;
		this.ascent = 68;
		this.descent = 0;
	}

	public void Display(int pointSize) {
		this.pointSize = pointSize;
		System.out.println(this.symbol + " (pointsize " + this.pointSize + ")");
	}
}

public class CharacterFactory {

	private Hashtable characters = new Hashtable();

	public Character GetCharacter(char key) {
		// Uses "lazy initialization"
		Character character = (Character) characters.get(key);
		if (character == null) {
			switch (key) {
			case 'A':
				character = new CharacterA();
				break;
			case 'B':
				character = new CharacterB();
				break;
			//
			case 'Z':
				character = new CharacterZ();
				break;
			}
			characters.put(key, character);
		}
		return character;
	}
}

public class Client {

	public static void main(String[] args) {
		
		String document = "AAZZBBZB";
		char[] chars = document.toCharArray();
		CharacterFactory f = new CharacterFactory();
		int pointSize = 10;
		for (char c : chars) {
			pointSize++;
			Character character = f.GetCharacter(c);
			character.Display(pointSize);
		}
	}
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值