抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。
这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
抽象工厂模式包含以下几个核心角色:
抽象工厂(Abstract Factory):声明了一组用于创建产品对象的方法,每个方法对应一种产品类型。抽象工厂可以是接口或抽象类。
具体工厂(Concrete Factory):实现了抽象工厂接口,负责创建具体产品对象的实例。
抽象产品(Abstract Product):定义了一组产品对象的共同接口或抽象类,描述了产品对象的公共方法。
具体产品(Concrete Product):实现了抽象产品接口,定义了具体产品的特定行为和属性。
抽象工厂:
- public abstract class AbstructFactory
- {
- public abstract Comptuter GetComptuter(string name);
- public abstract Phone GetPhone(string name);
- }
具体工厂:
- internal class ComptuterFactory : AbstructFactory
- {
- public override Comptuter GetComptuter(string name)
- {
- Comptuter comptuter = null;
- switch (name)
- {
- case "Apple":
- comptuter = new AppleComptuter();
- break;
- case "Dell":
- comptuter = new DellComptuter();
- break;
- case "Lesson":
- comptuter = new LessonComptuter();
- break;
- }
-
- return comptuter;
- }
-
- public override Phone GetPhone(string name)
- {
- Phone phone = null;
- switch (name)
- {
- case "Apple":
- phone = new ApplePhone();
- break;
- case "ReMi":
- phone = new ReMiPhone();
- break;
- case "HauWei":
- phone = new HauWeiPhone();
- break;
- }
-
- return phone;
- }
- }
-
-
- internal class PhoneFactory : AbstructFactory
- {
- public override Comptuter GetComptuter(string name)
- {
- Comptuter comptuter = null;
- switch (name)
- {
- case "Apple":
- comptuter = new AppleComptuter();
- break;
- case "Dell":
- comptuter = new DellComptuter();
- break;
- case "Lesson":
- comptuter = new LessonComptuter();
- break;
- }
-
- return comptuter;
- }
-
- public override Phone GetPhone(string name)
- {
- Phone phone = null;
- switch (name)
- {
- case "Apple":
- phone = new ApplePhone();
- break;
- case "ReMi":
- phone = new ReMiPhone();
- break;
- case "HauWei":
- phone = new HauWeiPhone();
- break;
- }
-
- return phone;
- }
- }
抽象产品:
- public abstract class Comptuter
- {
- public abstract string Name();
- }
-
-
- public abstract class Phone
- {
- public abstract string Name();
- }
具体产品:
- internal class ReMiPhone : Phone
- {
- public override string Name()
- {
- return "小米手机";
- }
- }
-
-
- internal class DellComptuter : Comptuter
- {
- public override string Name()
- {
- return "戴尔电脑";
- }
- }
具体使用:
- AbstructFactory a = new ComptuterFactory();
- AbstructFactory b = new PhoneFactory();
-
- Cp1 = a.GetComptuter("Dell").Name();
- Cp2 = a.GetComptuter("Apple").Name();
- Cp3 = a.GetComptuter("Lesson").Name();
-
- Ph1 = b.GetPhone("Apple").Name();
- Ph2 = b.GetPhone("ReMi").Name();
- Ph3 = b.GetPhone("HauWei").Name();