工厂设计模式和关键字“新” [英] Factory Design pattern and keyword 'new'

查看:151
本文介绍了工厂设计模式和关键字“新”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名初学者。我知道OOP的基础知识,但我还不知道最佳实践。例如,在编程中继续出现的一个范例是抽象工厂设计模式,这似乎相当简单。背后的一个关键意图是避免关键字新,因为它被认为是有害的。我在编程课程中从未听过这个。有人可以在这一点上阐述吗?为什么要避免以这种形式实例化对象?

解决方案

在您写的客户端/调用者类中考虑:

 车辆v =新车(宝马); 

如果你的代码像上面那样,你总是得到一辆汽车。将来如果您真的想要一个平面,您将不得不更新客户端代码。



或者,您使用工厂模式,您代码如下:

 车辆v = Factory.getVehicle(); 

现在,您可以保持从客户端和客户端获取车辆(松耦合)的逻辑如果你必须更新你得到的最终车辆,永远不会需要改变。只有工厂实施将更新,您的客户将按原样工作。


I'm a beginning programmer. I know the basics in OOP, but I don't know the "best practices" just yet. For instance, one paradigm that continues to come up in programming is the "Abstract Factory" design pattern, which seems fairly straightforward. One of the key intents behind it is to avoid the keyword "new", because it's considered harmful. I never heard this in the courses I took in programming. Could someone elaborate on that point? Why do we want to avoid instantiating objects in this form?

解决方案

Consider in your client / caller class you write:

Vehicle v = new Car("BMW");

If your code is like the one above, you will always get a Car. In the future if you actually want a Plane, you will have to update the client code.

Alternatively, you use a factory pattern, you code something like:

Vehicle v = Factory.getVehicle();

Now you can keep the logic of getting the vehicle away (loose coupling) from the client and your client would never need a change in case you have to update the end vehicle you get. Only the Factory implementation will update and your clients will work as is.

这篇关于工厂设计模式和关键字“新”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆