Factory Pattern (4)
设计模式原则:
依赖于抽象进行设计,而不是具体的实现。
工厂模式:
定义创建对象的接口,让其派生类去决定该创建什么类型的实例。
示例代码:
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using
System.Security.Cryptography;
namespace Hello
{
//Pizza
public
abstract class Pizza
{
protected
string name;
protected
string dough;
protected
string sauce;
public
void prepare()
{
Console.WriteLine("Prepare {0}", name);
Console.WriteLine("Tossing dough...");
Console.WriteLine("Adding sauce...");
}
public
void bake()
{
Console.WriteLine("Bake for 25 mins at 350");
}
public
void cut()
{
Console.WriteLine("Cutting the pizza into diagonal slices");
}
public
void box()
{
Console.WriteLine("Place pizza in official PizzaStore box");
}
public
string GetName()
{
return
name;
}
}
//NYStyleCheesePizza
public
class NYStyleCheesePizza
: Pizza
{
public
NYStyleCheesePizza()
{
name = "NY Style Sauce and Cheese Pizza";
dough = "Thin Crust Dough";
sauce = "Marinara Sauce";
}
}
//ChicagoStyleCheesePizza
public
class ChicagoStyleCheesePizza
: Pizza
{
public
ChicagoStyleCheesePizza()
{
name = "Chicago Style Deep Dish Cheese Pizza";
dough = "Extra Thick Crust Dough";
sauce = "Plum Tomato Sauce";
}
}
//Pizza
Store
public
abstract class PizzaStore
{
public
Pizza OrderPizza(string
type)
{
Pizza
pizza;
pizza = CreatePizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return
pizza;
}
protected
abstract Pizza
CreatePizza(string type);
}
//NYStylePizzaStore
public
class NYStylePizzaStore
: PizzaStore
{
protected
override Pizza
CreatePizza(string type)
{
if
(type == "cheese")
{
return
new NYStyleCheesePizza();
}
else
{
return
null;
}
}
}
//ChicagoStylePizzaStore
public
class ChicagoStylePizzaStore
: PizzaStore
{
protected
override Pizza
CreatePizza(string type)
{
if
(type == "cheese")
{
return
new ChicagoStyleCheesePizza();
}
else
{
return
null;
}
}
}
class
Program
{
static
void Main(string[]
args)
{
PizzaStore
pizzaStore1 = new NYStylePizzaStore();
Pizza
pizza1 = pizzaStore1.OrderPizza("cheese");
Console.WriteLine(pizza1.GetName());
Console.WriteLine();
PizzaStore
pizzaStore2 = new ChicagoStylePizzaStore();
Pizza
pizza2 = pizzaStore2.OrderPizza("cheese");
Console.WriteLine(pizza2.GetName());
}
}
}