首页 > 其他分享 >创建型——原型模式

创建型——原型模式

时间:2023-05-27 16:44:58浏览次数:39  
标签:ShapeforPrototypePattern 对象 创建 模式 原型 Console public

推荐文档:

https://www.cnblogs.com/zhili/p/DesignPatternSummery.html

https://www.runoob.com/design-pattern/design-pattern-tutorial.html

什么是原型模式?

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式之一。

这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

相关介绍

意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

主要解决:在运行期建立和删除原型。

何时使用

1、当一个系统应该独立于它的产品创建,构成和表示时。

2、当要实例化的类是在运行时刻指定时,例如,通过动态装载。

3、为了避免创建一个与产品类层次平行的工厂类层次时。

4、当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

如何解决:利用已有的一个原型对象,快速地生成和原型对象一样的实例。

关键代码

1、实现克隆操作,在 JAVA 实现 Cloneable 接口,重写 clone(),在 .NET 中可以使用 Object 类的 MemberwiseClone() 方法来实现对象的浅拷贝或通过序列化的方式来实现深拷贝。

2、原型模式同样用于隔离类对象的使用者和具体类型(易变类)之间的耦合关系,它同样要求这些"易变类"拥有稳定的接口。

应用实例

1、细胞分裂。

2、JAVA 中的 Object clone() 方法。

优点

1、性能提高。

2、逃避构造函数的约束。

缺点

1、配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。

2、必须实现 Cloneable 接口。

使用场景

1、资源优化场景。

2、类初始化需要消化非常多的资源,这个资源包括数据、硬件资源等。

3、性能和安全要求的场景。

4、通过 new 产生一个对象需要非常繁琐的数据准备或访问权限,则可以使用原型模式。

5、一个对象多个修改者的场景。

6、一个对象需要提供给其他对象访问,而且各个调用者可能都需要修改其值时,可以考虑使用原型模式拷贝多个对象供调用者使用。

7、在实际项目中,原型模式很少单独出现,一般是和工厂方法模式一起出现,通过 clone 的方法创建一个对象,然后由工厂方法提供给调用者。原型模式已经与 Java 融为浑然一体,大家可以随手拿来使用。

注意事项

与通过对一个类进行实例化来构造新对象不同的是,原型模式是通过拷贝一个现有对象生成新对象的。浅拷贝实现 Cloneable,重写,深拷贝是通过实现 Serializable 读取二进制流。

相关实现

我们将创建一个抽象类 Shape 和扩展了 Shape 类的实体类。下一步是定义类 ShapeCache,该类把 shape 对象存储在一个 Hashtable 中,并在请求的时候返回它们的克隆。

PrototypePatternDemo 类使用 ShapeCache 类来获取 Shape 对象。

 

  1 namespace Biao.DesignPatterns.CreationalPatterns
  2 {
  3     /// <summary>
  4     /// 创建一个实现了调用Object对象的MemberwiseClone方法的Clone方法的抽象类。
  5     /// </summary>
  6     public abstract class ShapeforPrototypePattern
  7     {
  8         private int id;
  9         protected string type;
 10 
 11         public int Id
 12         {
 13             set { id = value; }
 14             get { return id; }
 15         }
 16 
 17         public string GetType()
 18         {
 19             return type;
 20         }
 21 
 22         public abstract void Draw();
 23 
 24         public Object Clone()
 25         {
 26             Object clone = null;
 27             try
 28             {
 29                 clone = base.MemberwiseClone();
 30             }
 31             catch
 32             {
 33                 Console.WriteLine("Clone出错!");
 34             }
 35             return clone;
 36         }
 37     }
 38 
 39     /// <summary>
 40     /// 创建了扩展ShapeforPrototypePattern抽象类的实体类RectangleforPrototypePattern
 41     /// </summary>
 42     public class RectangleforPrototypePattern : ShapeforPrototypePattern
 43     {
 44         public RectangleforPrototypePattern()
 45         {
 46             type = "Rectangle";
 47         }
 48 
 49         public override void Draw()
 50         {
 51             Console.WriteLine("Rectangle内的Draw方法");
 52         }
 53     }
 54 
 55     /// <summary>
 56     /// 创建了扩展ShapeforPrototypePattern抽象类的实体类SquareforPrototypePattern
 57     /// </summary>
 58     public class SquareforPrototypePattern : ShapeforPrototypePattern
 59     {
 60         public SquareforPrototypePattern()
 61         {
 62             type = "Square";
 63         }
 64 
 65         public override void Draw()
 66         {
 67             Console.WriteLine("Square内的Draw方法");
 68         }
 69     }
 70 
 71     /// <summary>
 72     /// 创建了扩展ShapeforPrototypePattern抽象类的实体类CircleforPrototypePattern
 73     /// </summary>
 74     public class CircleforPrototypePattern : ShapeforPrototypePattern
 75     {
 76         public CircleforPrototypePattern()
 77         {
 78             type = "Circle";
 79         }
 80 
 81         public override void Draw()
 82         {
 83             Console.WriteLine("Circle内的Draw方法");
 84         }
 85     }
 86 
 87     /// <summary>
 88     /// 创建一个类,从数据库获取实体类,并把它们存储在一个 Hashtable 中。
 89     /// </summary>
 90     public class ShapeCache
 91     {
 92         private static Hashtable shapeMap = new Hashtable();
 93 
 94         public static ShapeforPrototypePattern GetShape(int shapeId)
 95         {
 96             ShapeforPrototypePattern cachedShape = (ShapeforPrototypePattern)shapeMap[shapeId];
 97             return (ShapeforPrototypePattern)cachedShape.Clone();
 98         }
 99 
100         public static void LoadCache()
101         {
102             CircleforPrototypePattern circle = new CircleforPrototypePattern();
103             circle.Id = 1;
104             shapeMap.Add(circle.Id, circle);
105 
106             SquareforPrototypePattern square = new SquareforPrototypePattern();
107             square.Id = 2;
108             shapeMap.Add(square.Id, square);
109 
110             RectangleforPrototypePattern rectangle = new RectangleforPrototypePattern();
111             rectangle.Id = 3;
112             shapeMap.Add(rectangle.Id, rectangle);
113         }
114     }
115 }
116  
117 
118 static void TestPrototypePattern()
119 {
120     Console.WriteLine("---------------测试原型模式---------------");
121     Biao.DesignPatterns.CreationalPatterns.ShapeCache.LoadCache();
122 
123     ShapeforPrototypePattern cloneShape = (ShapeforPrototypePattern)ShapeCache.GetShape(1);
124     Console.WriteLine("Shape:" + cloneShape.GetType());
125 
126     ShapeforPrototypePattern cloneShape2 = (ShapeforPrototypePattern)ShapeCache.GetShape(2);
127     Console.WriteLine("Shape:" + cloneShape2.GetType());
128 
129     ShapeforPrototypePattern cloneShape3 = (ShapeforPrototypePattern)ShapeCache.GetShape(3);
130     Console.WriteLine("Shape:" + cloneShape3.GetType());
131 }


标签:ShapeforPrototypePattern,对象,创建,模式,原型,Console,public
From: https://www.cnblogs.com/swbna/p/17436956.html

相关文章

  • 结构型——适配器模式
    推荐文档:https://www.cnblogs.com/zhili/p/DesignPatternSummery.htmlhttps://www.runoob.com/design-pattern/design-pattern-tutorial.html什么是适配器模式?适配器模式(AdapterPattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立......
  • 设计模式概述
    推荐文档:https://www.cnblogs.com/zhili/p/DesignPatternSummery.htmlhttps://www.runoob.com/design-pattern/design-pattern-tutorial.html为什么要使用设计模式?使用设计模式的根本原因是适应变化,为了增加代码复用率,是软件更具有维护性和可扩展性。设计原则单一职责原则......
  • 创建型——单例模式
    推荐文档:https://www.cnblogs.com/zhili/p/DesignPatternSummery.htmlhttps://www.runoob.com/design-pattern/design-pattern-tutorial.html什么是单例模式?单例模式(SingletonPattern)是最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方......
  • 设计模式之备忘录(Memento)
    概述备忘录模式(MementoPattern),是行为型模式设计模式之一,该模式用于保存对象当前状态,并且在之后可以再次恢复到此状态。备忘录模式实现的方式需要保证被保存的对象状态不能被对象从外部访问,目的是为了保护被保存的这些对象状态的完整性以及内部实现不向外暴露,本篇博客,我们就来......
  • 网安--vmware三种网络模式
    三、vmare三种网络模式三种模式:桥接模式、NAT模式、仅主机模式三种设备:网卡、路由器(充当网关宽展接口划分vlan)、交换机(局域网中的机器接入到一个网络中)vmnet0(桥接模式)、vmnet1(仅主机模式)、vmnet8(NAT模式)让相同网络模式的主机相互连接虚拟网卡:让主机与虚拟机连接起来1、主机......
  • ubuntu 20.4 安装msyql+创建mysql用户
    sudoapt-getupdatesudoapt-getupgratesudoaptinstallmysql-server设置运行远程访问修改:sudovim/etc/mysql/mysql.conf.d/mysqld.cnf用#注释掉bind-address=127.0.0.1进入mysql创建用户mysql-uroot-pCREATEUSER'test'@'%'IDENTIFIEDBY'12345......
  • 单例模式
    1、创建一个类将无参构造器变成私有权限(有两种实现方式)点击查看代码packagecom.bh.test;publicclassPerson{//(2)//privatestaticPersonperson;//将person变量定义成静态变量,因为getInstance()为静态方法只能调用静态变量privatestaticPersonp......
  • 行业报告 | AIGC应用与实践展望报告:人工智能重塑内容产业的作业模式
    原创|BFT机器人前言Introduction不可否认AIGC的出现似乎已经让大家预见了Al应用的拐点,其创造性与智能性一夜之间刷新了大众认知。但去伪存真,在市场火爆的背后其真正的应用及商业价值几何,更待我们冷静地剖析。01概念重生:AIGC是内容生成方式一次进化缘起于GC,而归于AI,AIGC的关键是A......
  • js原型prototype(实例构造函数的属性) __proto__(实例对象的属性) constructor(实例
    functionPerson(name,age){this.name=namethis.age=age}Person.prototype.sayHi=function(){//原型是公共方法解决构造函数new对象公共属性和方法的内存浪费console.log(this.name+'sayhi!!')}constp1=newPerson('aa',12)constp2=new......
  • 设计模式-观察者模式(Observer)
    一、 观察者(Observer)模式观察者模式又叫做发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通......