故事:
鞋子厂来了一个订单,需要一批(2双)运动鞋和一批(2双)休闲鞋。需要同样鞋码,但颜色不一样。
于是,老板决定使用同样的鞋模来生产小样,然后染色。
建模:
鞋子模型(原型) ——》 定码
运动鞋 ——》染色
休闲鞋 ——》染色
类图:
实现:
Shoes
namespace Prototype { public abstract class Shoes { public int size; protected string color; public string Color { set { color = Color; } get { return color; } } public int Size { set { size = Size; } get { return size; } } public abstract Shoes Clone(string color); } }
SportShoes
namespace Prototype { class SportShoes:Shoes { public SportShoes(int size,string color) { this.size = size; this.color = color; } public override Shoes Clone(string color) { return new SportShoes(this.size,color); } } }
LeisureShoes
namespace Prototype { class LeisureShoes: Shoes { bool indoor; public LeisureShoes(int size, string color, bool indoor) { this.size = size; this.color = color; this.indoor = indoor; } public override Shoes Clone(string color) { return new LeisureShoes(this.size, color, this.indoor); } } }
Program
namespace Prototype { class Program { static void Main(string[] args) { SportShoes shoes = new SportShoes(43,"Red"); SportShoes secondShoes = (SportShoes)shoes.Clone("Black"); LeisureShoes leisureShoes = new LeisureShoes(39, "Black", true); LeisureShoes secondLeisureShoes = (LeisureShoes)leisureShoes.Clone("White"); ArrayList al = new ArrayList(); al.Add(shoes); al.Add(secondShoes); al.Add(leisureShoes); al.Add(secondLeisureShoes); foreach (Shoes i in al) { Console.WriteLine("Size:{0},Color:{1}", i.Size, i.Color); } } } }
效果: