デザインパターン入門

Prototypeパターン

コピーしてインスタンスを作る.

どんな場合に使うのか

  1. 種類が多すぎて一つ一つをクラスにまとめられない場合.
  2. クラスからのインスタンス生成が難しい場合.newによる初期化は属性値が初期値に戻ってしまう.
  3. フレームワークと生成するインスタンスを分けたい場合.

クラス図

ポイント

  • newによる実際のインスタンス生成を,インスタンス生成のためのメソッド呼び出しに代えることで,具体的なクラス名による束縛からスーパークラスを解放している。

サンプルプログラム

// Manager.cs
using System;
using System.Collections.Generic;

namespace chap06 {
  namespace framework {
    public class Manager {
      private Dictionary<String, Product> showcase = new Dictionary<String, Product>();
      public void register(String name, Product proto) {
        showcase.Add(name, proto);
      }
      public Product create(String protoname) {
        Product p = showcase[protoname];
        return (Product)p.Clone();
      }
    }
  }
}

// MessageBox.cs
using System;
using chap06.framework;

namespace chap06 {
  public class MessageBox : Product {
    private Char decochar;
    public MessageBox(Char decochar) {
      this.decochar = decochar;
    }
    public void use(String s) {
      int length = s.Length;
      for (int i = 0; i < length + 4; i++) {
        Console.Write(decochar);
      }
      Console.WriteLine("");
      Console.WriteLine(s);
      for (int i = 0; i < length + 4; i++) {
        Console.Write(decochar);
      }
      Console.WriteLine("");
    }
    public object Clone() {
      return this.MemberwiseClone();
    }
  }
}


// Product.cs
using System;

namespace chap06 {
  namespace framework {
    public interface Product : ICloneable {
      void use(String s);
    }
  }
}

// Program.cs
using System;
using chap06.framework;

namespace chap06 {
  class Program {
    static void Main(string[] args) {
      Manager manager = new Manager();
      UnderlinePen upen = new UnderlinePen('~');
      MessageBox mbox = new MessageBox('*');
      MessageBox sbox = new MessageBox('/');

      manager.register("strong message", upen);
      manager.register("warning box", mbox);
      manager.register("slash box", sbox);

      Product p1 = (Product)manager.create("strong message");
      p1.use("Hello,world.");
      Product p2 = (Product)manager.create("warning box");
      p2.use("Hello,world.");
      Product p3 = (Product)manager.create("slash box");
      p3.use("Hello,world.");
      Console.Read();
    }
  }
}

// UnderlinePen.cs
using System;
using chap06.framework;

namespace chap06 {
  public class UnderlinePen : Product {
    private Char decochar;
    public UnderlinePen(Char decochar) {
      this.decochar = decochar;
    }
    public void use(String s) {
      int length = s.Length;
      Console.WriteLine(s);
      for (int i = 0; i < length + 20; i++) {
        Console.Write(decochar);
      }
      Console.WriteLine("");
    }
    public object Clone() {
      return this.MemberwiseClone();
    }
  }
}
デザインパターン入門

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

管理人/副管理人のみ編集できます