gpt4 book ai didi

c# - 这是表示抽象工厂模式的好例子吗

转载 作者:太空狗 更新时间:2023-10-29 21:10:48 25 4
gpt4 key购买 nike

想检查这是否是表示抽象工厂模式的好例子。这里是主题戴尔(工厂)制造 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.

在这种情况下,您将已知类型“硬编码”到枚举中,这违反了模式的这一部分。

关于c# - 这是表示抽象工厂模式的好例子吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5109093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com