工厂模式的优势是什么? [英] what's the advantage of factory pattern?

查看:169
本文介绍了工厂模式的优势是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

工厂方法模式的实际用途是什么?

抽象工厂模式与工厂方法之间的差异

我目前对工厂的理解是,它可以通过输入字符串创建对象,例如

My current understanding of factory is that it can create object by a input string, say

Factory.create("mouse");
Factory.create("hamster");

此模式与新版本有什么优势?

What's the advantage of this pattern over new?

推荐答案

如果您想通过共享工厂协调创建不同对象(在您的示例中为鼠标和仓鼠),工厂将非常有用。这可以用于(a)抽取公共超类的每个子类的特定构造方法细节(例如,在您的示例中为Animal)或(b)根据哪个对象(或动物)的类型向构造函数提供默认参数要创建。

A factory is useful if you want to "harmonize" the creation of different objects (in your example Mouse and Hamster) through a shared Factory. This can be used to (a) abstract away specific Constructor-details for each subclass of a common super class (e.g. Animal in your example) or (b) providing default arguments to a Constructor depending on which type of object (or animal) is to be created.

它可以用于统一共享共享的对象的创建,例如在缓存中:CacheFactory - > Memcache,Filecache,...使用每个缓存是相似的,但设置不同的缓存策略可能会有很大的不同。当使用工厂方法时,您可以更轻松地切换不同的缓存策略,最好只是修改一行代码工厂(Memcache,选项),而无需担心特定后端的复杂性;

It can be used to unify the creation of objects sharing a commonality, e.g. in caching: CacheFactory -> Memcache, Filecache, ... Working with each cache is similar, but setting up different caching strategies may differ vastly. When using the factory method you can switch between different caching strategies more easily, at best by just chaning one line of code factory("Memcache", options),without having to worry about the intricacies of the specific backend;

这篇关于工厂模式的优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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