标签:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace 享元模式 { //抽象棋子类 public abstract class AbstractChessman { //棋子坐标 protected int x; protected int y; //棋子类别(黑|白) protected string chess; public AbstractChessman (string chess) { this.chess = chess; } //点坐标设置 public abstract void point(int x,int y); //显示棋子信息 public void show() { Console.WriteLine(this.chess+ "("+this.x+","+this.y +")"); } } //黑色棋子实现 public class BlackChessman :AbstractChessman { public BlackChessman() : base("●") { Console.WriteLine("--BlackChessman Construction Exec!!!"); } public override void point(int x,int y) { this.x = x; this.y = y; this.show(); } } //白色棋子实现 public class WhiteChessman :AbstractChessman { public WhiteChessman() : base("○") { Console.WriteLine("--WhiteChessman Construction Exec!!!"); } public override void point(int x, int y) { this.x = x; this.y = y; this.show(); } } //创建棋子工厂 public class FiveChessmanFactory { //单例模式工厂 private static FiveChessmanFactory fiveChessmanFactory = new FiveChessmanFactory(); //缓存存放共享对象 private Hashtable cache = new Hashtable(); //私有化构造方法 private FiveChessmanFactory() { } //获得单例工厂 public static FiveChessmanFactory getInstance() { return fiveChessmanFactory; } public AbstractChessman getChessmanObject(string c) { //从缓存中获得棋子对象实例 AbstractChessman abstractChessman = (AbstractChessman)this.cache[c]; if (abstractChessman == null) { //缓存中没有棋子对象实例信息,则创建棋子对象实例,并放入缓存 switch (c) { case "B": abstractChessman = new BlackChessman(); break; case "W": abstractChessman = new WhiteChessman(); break; default: break; } //为防止非法字符的进入,返回null if (abstractChessman !=null) { cache.Add(c, abstractChessman); } } return abstractChessman; } } class Program { static void Main(string[] args) { //创建五子棋工厂 FiveChessmanFactory fiveChessmanFactory = FiveChessmanFactory.getInstance(); //随机数,用来生成棋子对象 Random random = new Random(); int radom = 0; AbstractChessman abstractChessman = null; for (int i = 0; i < 10; i++) { radom = random.Next(2); switch (radom) { case 0: abstractChessman = fiveChessmanFactory.getChessmanObject("B"); break; case 1: abstractChessman = fiveChessmanFactory.getChessmanObject("W"); break; } if (abstractChessman !=null) { //设置棋子位置信息 abstractChessman.point(i, random.Next(15)); } } } } }
标签:
原文地址:http://www.cnblogs.com/bhlsheji/p/4209208.html