模式介绍
Factory Method模式是一个Creation模式,它定义了用于创建对象的接口,但是没有指定该接口的各个实现将实例化什么对象。
这意味着,当使用这个模式时,您可以定义对象的某些方法和属性,这些方法和属性对于使用Factory方法创建的所有对象都是通用的,但是让各个Factory方法定义它们将实例化的特定对象。
示例
我们还是使用三明治举例子
三明治组成抽象类
/// <summary>
/// Product
/// </summary>
abstract class Ingredient { }
三明治组成具体类
/// <summary>
/// Concrete Product
/// </summary>
class Bread : Ingredient { }
/// <summary>
/// Concrete Product
/// </summary>
class Turkey : Ingredient { }
/// <summary>
/// Concrete Product
/// </summary>
class Lettuce : Ingredient { }
/// <summary>
/// Concrete Product
/// </summary>
class Mayonnaise : Ingredient { }
创建三明治的抽象类
/// <summary>
/// Creator
/// </summary>
abstract class Sandwich
{
private List<Ingredient> _ingredients = new List<Ingredient>();
public Sandwich()
{
CreateIngredients();
}
//Factory method
public abstract void CreateIngredients();
public List<Ingredient> Ingredients
{
get { return _ingredients; }
}
}
创建三明治的具体类
(下面那个是个超级三明治...)
/// <summary>
/// Concrete Creator
/// </summary>
class TurkeySandwich : Sandwich
{
public override void CreateIngredients()
{
Ingredients.Add(new Bread());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Bread());
}
}
/// <summary>
/// Concrete Creator
/// </summary>
class Dagwood : Sandwich
{
public override void CreateIngredients()
{
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
Ingredients.Add(new Turkey());
Ingredients.Add(new Turkey());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
}
}
客户端调用
class Program
{
static void Main(string[] args)
{
var turkeySandwich = new TurkeySandwich();
var dagwood = new Dagwood();
//Do something with these sandwiches (like, say, eat them).
...
}
}
总结
Factory Method模式提供了一种可以实例化对象的方式,但是创建这些实例的细节由实例类自己定义。
源代码
https://github.com/exceptionnotfound/DesignPatterns/tree/master/FactoryMethodPattern
原文
https://www.exceptionnotfound.net/the-daily-design-pattern-factory-method/