简单工厂模式和工厂方法模式[Factory Pattern]
//简单工厂模式
public abstract class pizza
{ }
public class pizzaA : pizza
{ }
public class pizzaB : pizza
{ }
//现在这个pizza可以为许多需要pizza信息"客户"服务
public class simplePizzaFactory
{
public pizza createPizza(string type)
{
pizza p = null;
if (type == "A")
{
p = new pizzaA();
}
else if (type == "B")
{
p = new pizzaB();
}
return p;
}
}
public class pizzaStore
{
simplePizzaFactory factory;
public pizzaStore(simplePizzaFactory factory)
{
this.factory = factory;
}
public pizza OrderPizza(string type)
{
return factory.createPizza(type);
//do somethingelse
}
}
class Program
{
static void Main(string[] args)
{
simplePizzaFactory factory=new simplePizzaFactory();
pizzaStore store = new pizzaStore(factory);
store.OrderPizza("A");
Console.Read();
}
}
public abstract class pizza
{ }
public class pizzaA : pizza
{ }
public class pizzaB : pizza
{ }
//现在这个pizza可以为许多需要pizza信息"客户"服务
public class simplePizzaFactory
{
public pizza createPizza(string type)
{
pizza p = null;
if (type == "A")
{
p = new pizzaA();
}
else if (type == "B")
{
p = new pizzaB();
}
return p;
}
}
public class pizzaStore
{
simplePizzaFactory factory;
public pizzaStore(simplePizzaFactory factory)
{
this.factory = factory;
}
public pizza OrderPizza(string type)
{
return factory.createPizza(type);
//do somethingelse
}
}
class Program
{
static void Main(string[] args)
{
simplePizzaFactory factory=new simplePizzaFactory();
pizzaStore store = new pizzaStore(factory);
store.OrderPizza("A");
Console.Read();
}
}
//设计模式原则:要依赖抽象,不要依赖具体类
//工厂方法模式
//定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个
//工厂方法让类把实例化推迟到子类
public abstract class pizza
{ }
public class pizzaA : pizza
{ }
public class pizzaB : pizza
{ }
//这是抽象创建者类,它定义了一个抽象的工厂方法
//让子类实现此方法制造产品
public abstract class pizzaStore
{
protected abstract pizza CreatePizza(string type);
public pizza OrderPizza(string type)
{
pizza p = CreatePizza(type);
//do somethingelse
return p;
}
}
public class StoreA : pizzaStore
{
protected override pizza CreatePizza(string type)
{
if (type == "A")
{
return new pizzaA();
}
else if (type == "B")
{
return new pizzaB();
}
else return null;
}
}
class Program
{
static void Main(string[] args)
{
pizzaStore storeA = new StoreA();
storeA.OrderPizza("A");
Console.Read();
}
}
//定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个
//工厂方法让类把实例化推迟到子类
public abstract class pizza
{ }
public class pizzaA : pizza
{ }
public class pizzaB : pizza
{ }
//这是抽象创建者类,它定义了一个抽象的工厂方法
//让子类实现此方法制造产品
public abstract class pizzaStore
{
protected abstract pizza CreatePizza(string type);
public pizza OrderPizza(string type)
{
pizza p = CreatePizza(type);
//do somethingelse
return p;
}
}
public class StoreA : pizzaStore
{
protected override pizza CreatePizza(string type)
{
if (type == "A")
{
return new pizzaA();
}
else if (type == "B")
{
return new pizzaB();
}
else return null;
}
}
class Program
{
static void Main(string[] args)
{
pizzaStore storeA = new StoreA();
storeA.OrderPizza("A");
Console.Read();
}
}