Prototype Pattern, C# implementation:
//Prototype design pattern implementation in C#
//------------------------------------
using System;
using System.Collections;
namespace PrototypePattern
{
// "Prototype"
abstract class GoodsProto
{
// Methods
public abstract GoodsProto Clone();
}
//--------------------------------------
// "ConcretePrototype"
class Goods : GoodsProto
{
// Fields
private string m_title;
private int m_group;
private int m_weight;
private double m_prise;
private int m_qty;
// Constructor
public Goods( string title, int group, int weight, double prise, int quantity)
{
m_title = title;
m_group = group;
m_weight = weight;
m_prise = prise;
m_qty = quantity;
}
// Methods
public override GoodsProto Clone()
{
// Creates a 'shallow copy'
return (GoodsProto) this.MemberwiseClone();
}
public void PrintInfo()
{
Console.WriteLine( "Goods title: {0}, group: {1}, weight: {2}, prise: {3}, quantity: {4}. Amount for {0}: {5}",
m_title, m_group, m_weight, m_prise, m_qty, m_prise*m_qty );
}
}
//--------------------------------------
// Object manager
class StoreHouse
{
private Hashtable m_goods = new Hashtable();
// Indexers
public GoodsProto this[ string name ]
{
get{ return (GoodsProto)m_goods[ name ]; }
set{ m_goods.Add( name, value ); }
}
}
//--------------------------------------
class PrototypeTest
{
public static void Main( string[] args )
{
StoreHouse storehouse = new StoreHouse();
// Initialize goods
storehouse[ "flatiron" ] = new Goods( "flatiron", 1, 10, 20.1, 10 );
storehouse[ "mobile nokia 12345" ] = new Goods( "mobile nokia 12345", 2, 3, 7.2, 15 );
string goodsTitle = "flatiron";
Goods f1 = (Goods)storehouse[ goodsTitle ].Clone();
f1.PrintInfo();
Console.Read();
}
}
}
|