使用哪种设计模式?
最近的一次采访中有人问我:
三明治应该正好有两片面包 (两端各一个),以及中间任意正数的奶酪。
Sandwich s = new Sandwich();
s.add(new BreadSlice());
s.add(new CheddarCheese());
s.add(new SwissCheese());
s.add(new BreadSlice());
System.println("My sandwich: "+ s.toString());
您可以使用什么设计模式来确保实例化的每个三明治都是有效的三明治?
I was asked in a recent interview:
A Sandwich should have exactly two slices of bread
(one on each end), and any positive number of Cheeses in between.
Sandwich s = new Sandwich();
s.add(new BreadSlice());
s.add(new CheddarCheese());
s.add(new SwissCheese());
s.add(new BreadSlice());
System.println("My sandwich: "+ s.toString());
What design pattern could you use to ensure that every Sandwich instantiated is a valid sandwich?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
Builder
模式:用于非常复杂的多步骤对象构造,其中构造函数或方法参数的数量会高得离谱。不完整
SandwichBuilders<如果在调用
.getSandwich()
时未正确完成,/code> 可能会抛出某种IncompleteSandwichException
。注意: 使用正确命名的构造方法,您不需要按特定顺序执行任何操作。
或者您可以使用
FactoryMethod
模式: 当步骤数适合具有合理数量参数的单个方法调用时,并且应保证对象处于完整状态。或者使用
构造函数
: 这是一个特例FactoryMethod
模式重载构造函数以允许添加奶酪:
有很多方法可以做到这一点,具体取决于您希望构造的严格程度。
例如,您可以将
Sandwich
实现设为Factory/Builder
对象的内部类
,并将其构造函数设为私有
所以它不能被错误地实例化。You could use a
Builder
pattern: Used for very complicated multi-step object construction, where the number of constructor or method arguments would be ridiculously high.incomplete
SandwichBuilders
could throw some kind ofIncompleteSandwichException
if not completed correctly when.getSandwich()
is called.Note: with properly named construction methods, you don't need to do anything in a specific order.
Or you could use a
FactoryMethod
pattern: When the number of steps would fit into a single method call with a reasonable number of arguments, and the object should be guaranteed to be a complete state.Or use the
Constructor
: which is a specialized case ofFactoryMethod
patternoverloaded constructor to allow for cheese addition:
There are lots of ways to do this depending on how strict you want the construction to be.
For example, you can make the
Sandwich
implementation aninner class
of theFactory/Builder
object and make its constructorprivate
so it can't be instantiated in-correctly.我认为 Builder 模式在这里可能是一个不错的选择。
I think the Builder pattern could be a good choice here.
我已经使用以下方法实现了该解决方案
虽然解决方案是用 C# 编写的,但可以轻松修改以在 Java 环境中运行。
I have implemented the solution using
Though the solution is in C# it can easily be modified to run in Java environment.