设计模式系列 - 原型模式
生活随笔
收集整理的這篇文章主要介紹了
设计模式系列 - 原型模式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
所謂原型模式是指為創(chuàng)建重復(fù)對象提供一種新的可能。
介紹
當(dāng)面對系統(tǒng)資源緊缺的情況下,如果我們在重新創(chuàng)建一個新的完全一樣的對象從某種意義上來講是資源的浪費,因為在新對象的創(chuàng)建過程中,是會有系統(tǒng)資源的消耗,而為了盡可能的節(jié)省系統(tǒng)資源,我們有必要尋找一種新的方式來創(chuàng)建重復(fù)對象。
類圖描述
由于Shape 抽象類繼承了 ICloneable 接口,所以通過上圖我們可以發(fā)現(xiàn),所有具體的類型都繼承 Shape 抽象類,并實現(xiàn) Clone() 方法即可。
代碼實現(xiàn)
1、定義具有抽象基類
public abstract class Shape : ICloneable {private string id;protected string type;public abstract void Draw();public string GetId() => id;public string GetType() => type;public void SetId(string id) => this.id = id;public new object MemberwiseClone() => base.MemberwiseClone();public abstract object Clone(); }2、定義具體類型
public class Circle:Shape {public Circle() => type = "Circle";public override void Draw(){Console.WriteLine("I am a Circle");}public override object Clone(){Circle obj = new Circle();obj.type = type;obj.SetId(this.GetId());return obj;} }public class Rectangle:Shape {public Rectangle() => type = "Rectangle";public override void Draw(){Console.WriteLine("I am a Rectangle");}public override object Clone(){Rectangle obj = new Rectangle();obj.type = type;obj.SetId(this.GetId());return obj;} }public class Square:Shape {public Square() => type = "Square";public override void Draw(){Console.WriteLine("I am a Square");}public override object Clone(){Square obj = new Square();obj.type = type;obj.SetId(this.GetId());return obj;} }3、創(chuàng)建種子數(shù)據(jù)
public class ShapeCache {private static HashSet<Shape> shapeMap = new HashSet<Shape>();public static Shape GetShape(string shapeId){var cachedShape = shapeMap.FirstOrDefault(p => p.GetId() == shapeId);return (Shape) cachedShape?.Clone();}public static void LoadCache(){Circle circle = new Circle();circle.SetId("1");shapeMap.Add(circle);Square square = new Square();square.SetId("2");shapeMap.Add(square);Rectangle rectangle = new Rectangle();rectangle.SetId("3");shapeMap.Add(rectangle);} }4、上層調(diào)用
class Program {static void Main(string[] args){ShapeCache.LoadCache();Shape clonedShape1 = (Shape) ShapeCache.GetShape("1");Console.WriteLine(clonedShape1.GetType());clonedShape1.Draw();Shape clonedShape2 = (Shape)ShapeCache.GetShape("2");Console.WriteLine(clonedShape2.GetType());clonedShape2.Draw();Shape clonedShape3 = (Shape)ShapeCache.GetShape("3");Console.WriteLine(clonedShape3.GetType());clonedShape3.Draw();Console.ReadKey();} }總結(jié)
在 C# 中實現(xiàn)原型模式的關(guān)鍵是需要定義一個繼承 ICloneable 接口的抽象類,并在子類中重寫相應(yīng)的 Clone() 方法即可。
轉(zhuǎn)載于:https://www.cnblogs.com/hippieZhou/p/9940504.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的设计模式系列 - 原型模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jsp+javabean实现购物车
- 下一篇: 记使用talend从oracle抽取数据