工厂方法模式的现实世界示例
我刚刚读了工厂方法。我知道它提供了一种将实例化委托给子类的方法。但我无法理解在现实场景中可能的用途。
谁能给出一个典型的例子来展示如何使用工厂方法模式,以便我能够与我所读到的内容联系起来。
对于哪个工厂方法模式是最佳解决方案的问题陈述就足以清楚地说明这一点。
I just read Factory Method. I understand that it provides a way to delegate the instantiation to sub-classes. But I couldn't understand the possible uses in a real-world scenario.
Can anyone give one typical example showing how Factory method pattern can be used so that I can relate to what I have read.
A problem statement for which factory method pattern is the best solution would be sufficient to make it clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
实现工厂设计模式的类充当多个类之间的桥梁。考虑使用多个数据库服务器(例如 SQL Server 和 Oracle)的示例。如果您正在开发一个使用SQL Server数据库作为后端的应用程序,但将来需要将后端数据库更改为oracle,如果您没有按照工厂设计模式编写代码,则需要修改所有代码。
在工厂设计模式中,您只需做很少的工作即可实现这一点。实现工厂设计模式的类会照顾你并减轻你的负担。从数据库服务器切换根本不会打扰您。您只需要在配置文件中进行一些小的更改。
A class implementing factory design pattern works as bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as backend, but in future need to change backend database to oracle, you will need to modify all your code, if you haven’t written your code following factory design pattern.
In factory design pattern you need to do very little work to achieve this. A class implementing factory design pattern takes care for you and lessen your burden. Switching from database server won’t bother you at all. You just need to make some small changes in your configuration file.
静态创建的 php 代码示例:
为了使其更加动态(稍后修改较少):
An example php code with static creation:
To make it more dynamic (less modification later):
从我现在正在开发的 API:
在这个示例中,我使用工厂方法来创建某种类型的抽象工厂(示例中为 PICASA)。
这两种模式经常一起使用。
From API I'm developing right now:
In this example I use Factory Method to create Abstract Factory of a certain type (PICASA in the example).
These two patterns are often used together.
Zend_Db 在它的 Zend_Db_Adapter 类中使用它来允许创建基于从配置对象传递的数据库设置的不同类型的数据库对象。
Zend_Db uses it in it's Zend_Db_Adapter class to allow the creation of different kinds of database objects based on database settings passed through from a configuration object.
.NET 基类库 (BCL) 中的一个示例是Control.CreateControlsInstance,它由(Windows 窗体)Control 类的许多其他成员使用。
您可以重写此受保护的方法来提供您自己的控件集合,例如,当您实现自定义控件时。
One example from the .NET Base Class Library (BCL) is Control.CreateControlsInstance, which is is used by many other members of the (Windows Forms) Control class.
You can override this protected method to provide your own collection of controls, e.g. when you are implementing a custom control.