想检查这是否是表示抽象工厂模式的好例子.
这是主题
戴尔(工厂)生产xps(产品)
戴尔(工厂)生产inspiron(产品)
惠普(工厂)使特使(产品)
hp(工厂)制造presario(产品)
这是主题
戴尔(工厂)生产xps(产品)
戴尔(工厂)生产inspiron(产品)
惠普(工厂)使特使(产品)
hp(工厂)制造presario(产品)
BestBuy销售电脑.
//Abstract factory abstract class ComputerFactory { public abstract Computer BuildComputer(Computer.ComputerType compType); } //Concrete factory class Dell : ComputerFactory { public override Computer BuildComputer(Computer.ComputerType compType) { if (compType == Computer.ComputerType.xps) return (new xps()); else if (compType == Computer.ComputerType.inspiron) return new inspiron(); else return null; } } //Concrete factory class Hp : ComputerFactory { public override Computer BuildComputer(Computer.ComputerType compType) { if (compType == Computer.ComputerType.envoy) return (new envoy()); else if (compType == Computer.ComputerType.presario) return new presario(); else return null; } } //Abstract product public abstract class Computer { public abstract string Mhz { get; set; } public enum ComputerType { xps,inspiron,envoy,presario } } //Concrete product for DELL public class xps : Computer { string _mhz = string.Empty; public override string Mhz { get { return _mhz; } set { _mhz = value; } } } //Concrete product for DELL public class inspiron : Computer { string _mhz = string.Empty; public override string Mhz { get { return _mhz; } set { _mhz = value; } } } //Concrete product for HP public class envoy : Computer { string _mhz = string.Empty; public override string Mhz { get { return _mhz; } set { _mhz = value; } } } //Concrete product for HP public class presario : Computer { string _mhz = string.Empty; public override string Mhz { get { return _mhz; } set { _mhz = value; } } } public class BestBuy { ComputerFactory compFactory; Computer comp; public BestBuy(Computer.ComputerType compType) { if (compType == Computer.ComputerType.xps || compType == Computer.ComputerType.inspiron) compFactory = new Dell(); else compFactory = new Hp(); comp = compFactory.BuildComputer(compType); } public Computer Sell() { return comp; } }
提前致谢.
解决方法
这是模式部分的一个很好的例子.对象的基本构造是一个不错的例子,但逻辑依赖于单个Computer.ComputerType枚举.这个枚举需要事先知道每个工厂暴露的每种类型的计算机.
通常,使用抽象工厂的动机是从图片中抽象出这种类型的硬编码要求.最好不要使用单个枚举,而是添加ComputerType类,并允许工厂返回可用类型的集合.然后,您可以使用返回的ComputerType来构建新系统.
这允许您在不更改API的情况下添加其他工厂,这是抽象工厂模式的主要优点之一.阅读Abstract Factory Pattern – 其中一个要点是:
The client does not know (or care) which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products.
在这种情况下,您将已知类型“硬编码”到枚举中,这违反了模式的这一部分.