工厂设计模式和关键字“新” [英] Factory Design pattern and keyword 'new'
问题描述
在您写的客户端/调用者类中考虑:
车辆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屋!