⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 class1.cs

📁 《深入浅出设计模式》的完整源代码
💻 CS
字号:
using System;
using System.Collections;
// Flyweight工厂
class CharacterFactory
{
	private Hashtable characters = new Hashtable();
	public Character GetCharacter( char key )
	{
		//在初始化的Hastable中取出字符
		Character character = (Character)characters[ key ];
		//如取出的字符为null,初始化它
		if( character == null )
		{
			switch( key )
			{
				case 'A': character = new CharacterA(); break;
				case 'B': character = new CharacterB(); break;
					//...
				case 'Z': character = new CharacterZ(); break;
			}
			//将初始的字符加入Hashtable
			characters.Add( key, character );
		}
		return character;
	}
}
//Flyweight
abstract class Character
{
	protected char symbol;
	protected int width;
	protected int height;
	protected int ascent;
	protected int descent;
	protected int pointSize;
	public abstract void Draw( int pointSize );
}
// 具体Flyweight,字符A
class CharacterA : Character
{
	// 构造函数初始化字符特征
	public CharacterA( )
	{
		this.symbol = 'A';
		this.height = 100;
		this.width = 120;
		this.ascent = 70;
		this.descent = 0;
	}
	// 绘画出字符
	public override void Draw( int pointSize )
	{
		this.pointSize = pointSize;
		Console.Write( this.symbol );
	}
}

//具体Flyweight,字符B
class CharacterB : Character
{
	//构造函数初始化字符特征
	public CharacterB()
	{
		this.symbol = 'B';
		this.height = 100;
		this.width = 140;
		this.ascent = 72;
		this.descent = 0;
	}
	// 绘画出字符
	public override void Draw( int pointSize )
	{
		this.pointSize = pointSize;
		Console.Write( this.symbol );
	}
}
//省略 ... C, D, E, etc.
//具体Flyweight,字符Z
class CharacterZ : Character
{
	// 构造函数初始化字符特征
	public CharacterZ( )
	{
		this.symbol = 'Z';
		this.height = 100;
		this.width = 100;
		this.ascent = 68;
		this.descent = 0;
	}
	// 绘画出字符
	public override void Draw( int pointSize )
	{
		this.pointSize = pointSize;
		Console.Write( this.symbol );
	}
}
/// <summary>
///  Flyweight应用测试程序
/// </summary>
public class FlyweightApp
{
	public static void Main( string[] args )
	{
		// 用字符数组创造document
		char[] document = {'A','B','Z','Z','A','A'};
		CharacterFactory f = new CharacterFactory();
		//外部的状态
		int pointSize = 12;
		//For each character use a flyweight object
		foreach( char c in document )
		{
			Character character = f.GetCharacter( c );
			character.Draw( pointSize );
		}
		Console.Read();
	}
}  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -