设计模式 单件 & 原型

Design Pattern - Singleton & Prototype

实现了单件模式的的Client, 它自身只有一个示例, 用Instance()方法得到惟一的实例

public class Client
{
    
static private Hashtable ht = new Hashtable();
    
static protected Client c = null;

    
protected Client()
    
{
    }


    
public static Client Instance()
    
{
        
if(c == null)
            c 
= new Client();
        
return c;
    }


    
public void Register(String name, CloneHuman ch)
    
{
        ht.Add(name, ch);
    }

        
public CloneHuman BuildCloneHuman(String name)
    
{
        CloneHuman ch 
= (CloneHuman)ht[name];
        
return ch.CreateClone();
    }

}

克隆人的类, 以及分别它的子类克隆的男人和女人
public class CloneHuman
{
    
public virtual CloneHuman CreateClone()
    
{
        
return null;
    }


    
public void Show()
    
{
        String s 
= this.GetType().ToString();
        Console.WriteLine(s.Substring(s.LastIndexOf(
".")+1));
    }

}
public class CloneMale : CloneHuman
{
    
public override CloneHuman CreateClone()
    
{
        
return (CloneHuman)this.MemberwiseClone();
    }

}

public class CloneFemale : CloneHuman
{
    
public override CloneHuman CreateClone()
    
{
        
return (CloneHuman)this.MemberwiseClone();
    }

}

测试程序

public static void Main()
{
    Client c 
= Client.Instance();
    CloneMale cm 
= new CloneMale();
    CloneFemale cf 
= new CloneFemale();
    c.Register(
"CloneMale", cm);
    c.Register(
"CloneFemale", cf);
    
for(Int32 i=0; i<10; i++)
    
{
        String name 
= (i%2==0)?"CloneMale":"CloneFemale";
        CloneHuman ch 
= c.BuildCloneHuman(name);
        ch.Show();
    }

    Console.ReadLine();
}
Prototype Demo
原文地址:https://www.cnblogs.com/Dabay/p/364762.html