简单工厂模式(入门)
简单工厂模式(又叫做静态工厂方法模式):由一个工厂根据传入的参数决定创造出哪种产品.
1.共3个角色:工厂类,具体产品,抽象产品.他们3者关系:工厂类生产具体产品,具体产品继承抽象产品.
2.优点:如果工厂缺少某个产品,直接创建产品.而不用更改代码.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace CA
{
class Program
{
static void Main(string[] args)
{
IFruit f = GardenManager.Factory("CA.Apple");
f.Grow();
Console.Read();
}
}
public interface IFruit
{
void Grow();
void Plant();
}
public class Apple : IFruit
{
public void Grow()
{
Console.Write("Apple is growing");
}
public void Plant()
{
Console.Write("Apple is planting");
}
}
public class Grape : IFruit
{
public void Grow()
{
Console.Write("Grape is growing");
}
public void Plant()
{
Console.Write("Grape is planting");
}
}
public class GardenManager
{
public static IFruit Factory(string which)
{
object f = Assembly.GetExecutingAssembly().CreateInstance(which); //利用反射弥补缺点
if (f == null)
{
throw new BadException("ee");
}
return f as IFruit;
}
}
public class BadException : Exception
{
public BadException(string message)
{
}
}
}

浙公网安备 33010602011771号