2021-02-15

Prototype原型模式

>>返回《C#常用设计模式》

  • 1. 简介
  • 2. 示例
  • 3. 优缺点
    • 3.1. 优点
    • 3.2. 缺点
    • 3.3. 原型模式的适用环境

1. 简介

  • 定义
    • 使用原型实例指定待创建对象的类型,并且通过复制这个原型来创建新的对象。
  • 使用场景
    • 频繁创建"结构复杂的对象"
  • 注意,克隆的对象是全新的对象,而且是独立

2. 示例

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Text.RegularExpressions;namespace ConsoleApplication4{ class Program {  static void Main(string[] args)  {   GameSys sys = new GameSys();   sys.Run(new NormalActorA(), new FlyActorA(), new WaterActorA());  } } public class GameSys {  public void Run(NormalActor normalActor, FlyActor flyActor, WaterActor waterActor)  {   NormalActor nActor1 = normalActor.Clone();   NormalActor nActor2 = normalActor.Clone();   NormalActor nActor3 = normalActor.Clone();   FlyActor fActor1 = flyActor.Clone();   FlyActor fActor2 = flyActor.Clone();   WaterActor wActor1 = waterActor.Clone();  } } #region 抽象类 public abstract class NormalActor {  public abstract NormalActor Clone(); } public abstract class FlyActor {  public abstract FlyActor Clone(); } public abstract class WaterActor {  public abstract WaterActor Clone(); } 

No comments:

Post a Comment