Factory method pattern(air: different from the abstract one)

本文主要介绍了工厂方法模式的应用。在抽象工厂的经典实现中,抽象类定义创建对象族的方法,派生类重写这些方法遵循工厂方法模式。有时创建与现有类结构平行的分层类结构时,工厂方法可用于实例化对应对象。此外,在定义框架时也常用该模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Field Notes: Using the Factory Method Pattern

Abstract Factory can be implemented as a family of Factory Methods


In the classic implementation of the Abstract Factory, I had an abstract class define the methods to create a family of objects. I derived a class for each different family I could have. Each of the methods defined in the abstract class and then overridden in the derived classes was following the Factory Method pattern.

Useful to bind parallel class hierarchies


Sometimes it is useful to create a hierarchical class structure that is parallel to an existing class structure, with the new hierarchy containing some delegated responsibilities. In this case, it is important for each object in the original hierarchy to be able to instantiate the proper object in the parallel hierarchy. A Factory Method can be used for this purpose. In the languages example mentioned previously, the Factory Method patterns bind the different collections with the different iterators associated with the collections, as shown in Figure 23-2.

Figure 23-2. Binding parallel class hierarchies.


The Factory Method Pattern: Key Features

Intent

Define an interface for creating an object, but let subclasses decide which class to instantiate. Defer instantiation to subclasses.

Problem

A class needs to instantiate a derivation of another class, but doesn't know which one. Factory Method allows a derived class to make this decision.

Solution

A derived class makes the decision on which class to instantiate and how to instantiate it.

Participants and collaborators

Product is the interface for the type of object that the Factory Method creates. Creator is the interface that defines the Factory Method.

Consequences

Clients will need to subclass the Creator class to make a particular ConcreteProduct.

Implementation

Use a method in the abstract class that is abstract (pure virtual in C++). The abstract class' code refers to this method when it needs to instantiate a contained object but does not know which particular object it needs.


Figure 23-3. Generic structure of the Factory Method pattern.



Factory Method is used in frameworks


The Factory Method pattern is commonly used when defining frameworks. This is because frameworks exist at an abstract level. Usually they do not know and should not be concerned about instantiating specific objects. They need to defer the decisions about specific objects to the users of the framework.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值