• 设计模式 单件 & 原型


    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
  • 相关阅读:
    hdfs搭建常见问题
    [转]opencv与Labview的结合(Dll调用)
    [转]opencv二值化的cv2.threshold函数
    忙在比赛前
    [转]使用charls抓包微信小程序的解决方案
    [转]Python调用C语言
    [转]基于Python实现matplotlib中动态更新图片(交互式绘图)
    [转]Python十六进制与字符串的转换
    STM32学习日记
    [转]Linux下的softlink和hardlink
  • 原文地址:https://www.cnblogs.com/Dabay/p/364762.html
Copyright © 2020-2023  润新知