一定义:工厂方法模试不是用一个专门的类来决定实例化哪一个子类。而是,父类把这种决定延迟到每个子类。既由子类来决定要实例化谁。
二UML类图:
三模式角色与结构:
Product :定义工厂所要创建的抽象产品
ConcreteProduct:实现抽象产品的具体产品
Creator:声明工厂方法,返回抽象产品
ConcreteCreator:实现Creator,返回具体的产品
四程序举例:
使用工厂方法模式,写一个动物工厂。动物工厂中的动物有“吃东西”的行为。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FactoryMethod
{
abstract class Animals {
protected String name;
protected String food;
public abstract void eat();
protected String Food
{
get { return food; }
set { food = value; }
}
protected String Name
{
get { return name; }
set { name = value; }
}
}
class Dog : Animals
{
public Dog(String food)
{
this.name = "狗";
this.food = food;
}
public override void eat()
{
Console.WriteLine("Dog is Eatting"+this.food);
}
}
class Cat : Animals
{
public Cat(String food)
{
this.name = "猫";
this.food = food;
}
public override void eat()
{
Console.WriteLine("Cat is Eatting"+this.food);
}
}
interface IFactory {
Animals createAnimals(String str);
}
class DogFactory : IFactory
{
public Animals createAnimals(string str)
{
return new Dog(str);
}
}
class CatFacory : IFactory
{
public Animals createAnimals(string str)
{
return new Cat(str);
}
}
class Client
{
static void Main(string[] args)
{
IFactory Catfactory = new CatFacory();
IFactory Dogfactory = new DogFactory();
Dog dog = (Dog)Dogfactory.createAnimals("骨头");
Cat cat = (Cat)Catfactory.createAnimals("鱼");
dog.eat();
cat.eat();
}
}
}
效果显示: