/**************************************************************************
* @Copyright (c) 2013, ChenMH, All rights reserved.
* @file : Program.cs
* @version : ver 1.0
* @author : ChenMH
* @date : 2013/12/10 09:18
* @brief : C#设计模式之3:Factory
**************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace CS_Pattern__Factory
{
public abstract class ICommond
{
abstract public void test();
}
public class CommondA : ICommond
{
override public void test()
{
Console.WriteLine("CommondA:test()");
}
}
public class CommondB : ICommond
{
override public void test()
{
Console.WriteLine("CommondB:test()");
}
}
public class Factory
{
private ICommond cmd;
private Dictionary<string, ICommond> dictNP = new Dictionary<string, ICommond>();
/********************************************************
* @brief : 工厂单例
* @return : 返回工厂对像
* @author : ChenMH 2013/12/10 12:01
********************************************************/
private static Factory factory;
public static Factory GetInstance()
{
if (null == factory)
factory = new Factory();
return factory;
}
/********************************************************
* @brief : 产品生成
* @input : name 产品名称
* @return : 返回创建的对像
* @author : ChenMH 2013/12/10 11:21
********************************************************/
public ICommond Create(string name)
{
foreach (KeyValuePair<string, ICommond> k in dictNP)
{
if (name == k.Key)
return k.Value;
}
try
{
cmd = null;
if ("CommondA" == name)
cmd = new CommondA();
else if ("CommondB" == name)
cmd = new CommondB();
else
return null;
}
catch
{
throw;
}
dictNP.Add(name, cmd);
return cmd;
}
}
class Program
{
static void Main(string[] args)
{
ICommond cmdA1 = Factory.GetInstance().Create("CommondA");
if(null != cmdA1)
cmdA1.test();
ICommond cmdA2 = Factory.GetInstance().Create("CommondA");
}
}
}
C#实现命令工厂
最新推荐文章于 2023-01-02 13:18:28 发布