设计模式之 工厂方法模式
内容图解:
代码:
用工厂方法模式产生魔兽不同种族
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
* author:zzy
* describe:factory method pattern
*
* other: if want to add a new race named FifthRace,
* you can define a class named "FifthRace" that implements
* the interface IWar3Race,then,accomplish the Said method.
* besides this,you need to define a class "FifthRaceFactory"
* and implements the method GetRace();
* do not need to modify the code that have existed
* ##对修改关闭,对扩展开放##
*
*/
namespace FactoryMethod
{
class Program
{
#region client
static IFactory factory;
static IWar3Race war3Race;
static void Main(string[] args)
{
factory = new HumFactory();//hum
war3Race=factory.getRace();
war3Race.Said();
factory = new OrcFactory();//orc
war3Race=factory.getRace();
war3Race.Said();
factory = new UdFactory();//ud
war3Race=factory.getRace();
war3Race.Said();
factory = new NeFactory();//ne
war3Race=factory.getRace();
war3Race.Said();
Console.Read();
}
#endregion client
}
#region product
/// <summary>
/// product interface
/// </summary>
public interface IWar3Race
{
void Said();
}
/// <summary>
/// one product class named Hum
/// </summary>
public class Hum : IWar3Race
{
public void Said()
{
Console.Write("I am AM\r\n");
}
}
/// <summary>
/// one product class named Orc
/// </summary>
public class Orc : IWar3Race
{
public void Said()
{
Console.Write("I am BM\r\n");
}
}
/// <summary>
/// one product class named Ud
/// </summary>
public class Ud : IWar3Race
{
public void Said()
{
Console.Write("I am DK\r\n");
}
}
/// <summary>
/// one product class named Ne
/// </summary>
public class Ne : IWar3Race
{
public void Said()
{
Console.Write("I am DH\r\n");
}
}
#endregion product
#region factory
/// <summary>
/// factroy interface
/// </summary>
public interface IFactory
{
IWar3Race getRace();
}
/// <summary>
/// the factory used to product Hum
/// </summary>
public class HumFactory:IFactory
{
public IWar3Race getRace()
{
return new Hum();
}
}
/// <summary>
/// the factory used to product Orc
/// </summary>
public class OrcFactory:IFactory
{
public IWar3Race getRace()
{
return new Orc();
}
}
/// <summary>
/// the factory used to product Ud
/// </summary>
public class UdFactory : IFactory
{
public IWar3Race getRace()
{
return new Ud();
}
}
/// <summary>
/// the factory used to product Ne
/// </summary>
public class NeFactory : IFactory
{
public IWar3Race getRace()
{
return new Ne();
}
}
#endregion factory
}
运行结果:
欢迎转载,转载请注明出处