工厂方法模式:
工厂方法模式每个具体工厂类只完成单个实例的创建,所以它具有很好的可扩展性
但是在实际应用中,一个工厂不止会创建单一的产品,因为现在的工厂都多元化了,一个工厂创建一系列的产品,这就引入了抽象工厂的概念
抽象工厂模式
抽象工厂模式是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
/// <summary>
/// 抽象工厂类:提供创建不同品牌的手机屏幕和手机主板
/// </summary>
public abstract class AbstractFactory
{
//工厂生产屏幕
public abstract Screen CreateScreen();
//工厂生产主板
public abstract MotherBoard CreateMotherBoard();
}
/// <summary>
/// 屏幕抽象类:提供每一品牌的屏幕的继承
/// </summary>
public abstract class Screen
{
public abstract void print();
}
/// <summary>
/// 主板抽象类:提供每一品牌的主板的继承
/// </summary>
public abstract class MotherBoard
{
public abstract void print();
}
/// <summary>
/// 苹果手机屏幕
/// </summary>
public class AppleScreen:Screen
{
public override void print()
{
Console.WriteLine("苹果手机屏幕!");
}
}
/// <summary>
/// 苹果手机主板
/// </summary>
public class AppleMotherBoard:MotherBoard
{
public override void print()
{
Console.WriteLine("苹果手机主板!");
}
}
/// <summary>
/// 小米手机屏幕
/// </summary>
public class XiaoMiScreen:Screen
{
public override void print()
{
Console.WriteLine("小米手机屏幕!");
}
}
/// <summary>
/// 小米手机主板类
/// </summary>
public class XiaoMiMotherBoard :MotherBoard
{
public override void print()
{
Console.WriteLine("小米手机主板!");
}
}
/// <summary>
/// 苹果手机工厂
/// </summary>
public class AppleFactory : AbstractFactory
{
/// <summary>
/// 生产苹果手机屏幕
/// </summary>
/// <returns></returns>
public override Screen CreateScreen()
{
return new AppleScreen();
}
/// <summary>
/// 生产苹果手机主板
/// </summary>
/// <returns></returns>
public override MotherBoard CreateMotherBoard()
{
return new AppleMotherBoard();
}
}
/// <summary>
/// 小米手机工厂类
/// </summary>
public class XiaoMiFactory : AbstractFactory
{
/// <summary>
/// 生产小米手机屏幕
/// </summary>
/// <returns></returns>
public override Screen CreateScreen()
{
return new XiaoMiScreen();
}
/// <summary>
/// 生产小米手机主板
/// </summary>
/// <returns></returns>
public override MotherBoard CreateMotherBoard()
{
return new XiaoMiMotherBoard();
}
}
class Test
{
static void Main(string[] args)
{
//小米工厂生产小米手机的屏幕和主板
AbstractFactory xiaomiFactory = new XiaoMiFactory();
Screen xiaomiScreen = xiaomiFactory.CreateScreen();
xiaomiScreen.print();
MotherBoard xiaomiMotherBoard = xiaomiFactory.CreateMotherBoard();
xiaomiMotherBoard.print();
//苹果工厂生产苹果手机屏幕和主板
AbstractFactory appleFactory = new AppleFactory();
Screen appleScreen = appleFactory.CreateScreen();
appleScreen.print();
MotherBoard appleMotherBoard = appleFactory.CreateMotherBoard();
appleMotherBoard.print();
Console.Read();
}
}