owned this note
owned this note
Published
Linked with GitHub
DP10 仲介者模式(Mediator Pattern)、享元模式(Flyweight Pattern)
===
###### tags: `DesignPatterns`
參考
[Design Patterns Elements of Reusable Object-Oriented Software](http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf)
[大話設計模式](https://www.tenlong.com.tw/products/9789866761799)
[UML工具](https://plantuml-editor.kkeisuke.com/#)
[DesignPatternsPHP](https://github.com/domnikl/DesignPatternsPHP/blob/master/Behavioral/State/OrderContext.php)
[Head First Design Patterns: A Brain-friendly Guide](https://www.books.com.tw/products/F010315469)
[汤姆大叔的博客: 深入理解JavaScript系列](https://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html)
[從實例學設計模式 by Jace Ju](http://slides.com/jaceju/design-patterns-by-examples/#/)
[设计模式之美](https://www.cnblogs.com/gaochundong/p/design_patterns.html)
[UNC-GOF](http://www.cs.unc.edu/~stotts/GOF/hires/chap1fso.htm)
http://fabien.potencier.org/what-is-dependency-injection.html
# 仲介者模式(Mediator Pattern)
## 大話:
### 定義 :
仲介者模式(Mediator Pattern),用一個仲介物件來封裝一系列的物件互動。仲介者史個物件不需要顯示地互相參考,從而使其偶合鬆散,而且可以獨立地改變他們之間的互動。(p.378)
### 節錄:
儘管將一個系統分隔成許多物件通常可以增加其可複用性,但是物件間相連接的增又會降低其可複用性了。
因為大量的連接使得一個物件不可能在沒有其他物件的支援下工作,系統表現為一個不可分割的整體,所以,對系統的行為進行任何較大的改動就十分困難了。(p.377)
- 違反 **迪米特法則**
> 如何解決? 可以透過仲介者物件,將網狀結構變成以仲介者為中心的星狀結構。
物件之間透過仲介者進行溝通,使得系統的結構不會因為新物件的引入產生大量的修改工作。
### 優缺點:
1. 仲介者模式很容易在系統中應用,也很容易在系統中誤用。當系統出現了 **多對多** 互動複雜的物件群時,不要急於使用仲介者模式,而要先反省你的系統在設計上是不是合理。
2. Mediator 減少了各個 Colleague 的耦合,可以獨立的改變或複用各個 Colleague 和 Mediator。再者,由於把物件如何協作進行了抽象,將仲介作為一個獨立的概念並將其封裝在一個物件中,這樣讓我們可以將焦點從物件各自本身的行為轉移到他們之間的互動,可以站在更宏觀的角度觀察系統。
3. 由於 ConcreteMediator 將控制集中化,同時也將複雜的互動包含了進來,大大增加了仲介者的複雜性。
(p.387)
#### 使用時機:
仲介者模式一般應用於一組物件以定義良好但是複雜的方式進行通訊的場合,以及想訂製一個分布在多個類別中的行為,但又不想產生太多子類別的場合。
### 討論:
- 哪邊有用到呢?
- 哪邊可以用?
## GOF
## Command Pattern
### Intent
Define an object that encapsulates how a set of objects interact.Mediator promotes
loose coupling by keeping objects from referring toeach other explicitly, and
it lets you vary their interaction independently.
### Motivation
Object-oriented design encourages the distribution of behavior among objects. Such
distribution can result in an object structure with many connections between
objects; in the worst case, every object ends up knowing about every other.
Though partitioning a system into many objects generally enhance sreusability,
prolife rating interconnections tend to reduce it again.Lots of interconnections
make it less likely that an object can work without the support of others — the system
acts as though it were monolithic. Moreover, it can be difficult to change the
system's behavior in any significant way, since behavior is distributed among many
objects. As a result, you may be forced to define many subclasses to customize
the system's behavior.
As an example, consider the implementation of dialog boxes in agraphical user
interface. A dialog box uses a window to present acollection of widgets such as
buttons, menus, and entry fields, asshown here:

Often there are dependencies between the widgets in the dialog. For example, a
button gets disabled when a certain entry field is empty.Selecting an entry in
a list of choices called a list box might change the contents of an entry field.
Conversely, typing text into the entry field might automatically select one or
more corresponding entries in the list box. Once text appears in the entry field,
other buttons may become enabled that let the user do something with the text,
such as changing or deleting the thing to which it refers.
Different dialog boxes will have different dependencies between widgets. So even
though dialogs display the same kinds of widgets,they can't simply reuse stock
widget classes; they have to be customized to reflect dialog-specific dependencies.
Customizing them individually by subclassing will be tedious, since many classes
are involved.
You can avoid these problems by encapsulating collective behavior in aseparate
**mediator** object. A mediator is responsible for controlling and coordinating the
interactions of a group of objects.The mediator serves as an intermediary that
keeps objects in the group from referring to each other explicitly. The objects
only know the mediator, thereby reducing the number of interconnections.
For example, **FontDialogDirector** can be the mediator between the widgets in a dialog
box. A FontDialogDirector object knows the widgets in a dialog and coordinates
their interaction. It acts asa hub of communication for widgets:

The following interaction diagram illustrates how the objects cooperate tohandle
a change in a list box's selection:

Here's the succession of events by which a list box's selection passes to an entry
field:
1. The list box tells its director that it's changed.
2. The director gets the selection from the list box.
3. The director passes the selection to the entry field.
4. Now that the entry field contains some text, the directorenables button(s) for initiating an action (e.g., "demibold," "oblique").
Note how the director mediates between the list box and the entry field.Widgets
communicate with each other only indirectly, through thedirector. They don't have
to know about each other; all they know is thedirector. Furthermore, because the
behavior is localized in one class,it can be changed or replaced by extending
or replacing that class.
Here's how the FontDialogDirector abstraction can be integrated into aclass
library:

DialogDirector is an abstract class that defines the overall behavior ofa dialog.
Clients call the ShowDialog operation to display the dialog onthe screen.
CreateWidgets is an abstract operation for creating thewidgets of a dialog.
WidgetChanged is another abstract operation;widgets call it to inform their
director that they have changed.DialogDirector subclasses override CreateWidgets
to create the properwidgets, and they override WidgetChanged to handle the changes.
### Applicability
Use the Mediator pattern when
- a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.
- reusing an object is difficult because it refers to and communicates with many other objects.
- a behavior that's distributed between several classes should be customizable without a lot of subclassing.
### Structure

A typical object structure might look like this:

### Participants
- **Mediator** (DialogDirector)
- defines an interface for communicating with Colleague objects.
- **ConcreteMediator** (FontDialogDirector)
- implements cooperative behavior by coordinating Colleague objects.
- knows and maintains its colleagues.
- **Colleague classes** (ListBox, EntryField)
- each Colleague class knows its Mediator object.
- each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague.
### Collaborations
- Colleagues send and receive requests from a Mediator object. Themediator implements the cooperative behavior by routing requestsbetween the appropriate colleague(s).
### Consequences
The Mediator pattern has the following benefits and drawbacks:
1. **It limits subclassing.** A mediator localizes behavior that otherwise would
be distributed amongseveral objects. Changing this behavior requires
subclassing Mediatoronly; Colleague classes can be reused as is.
2. **It decouples colleagues.** A mediator promotes loose coupling between
colleagues. You can varyand reuse Colleague and Mediator classes
independently.
3. **It simplifies object protocols.** A mediator replaces many-to-many
interactions with one-to-manyinteractions between the mediator and its
colleagues. One-to-manyrelationships are easier to understand, maintain,
and extend.
4. **It abstracts how objects cooperate.** Making mediation an independent concept
and encapsulating it in anobject lets you focus on how objects interact
apart from theirindividual behavior. That can help clarify how objects
interact in asystem.
5. **It centralizes control.** The Mediator pattern trades complexity of
interaction for complexity inthe mediator. Because a mediator encapsulates
protocols, it can becomemore complex than any individual colleague. This
can make the mediatoritself a monolith that's hard to maintain.
### Implementation
The following implementation issues are relevant to the Mediatorpattern:
1. **Omitting the abstract Mediator class.** There's no need to define an abstract
Mediator class when colleagueswork with only one mediator. The abstract
coupling that theMediator class provides lets colleagues work with
different Mediatorsubclasses, and vice versa.
2. **Colleague-Mediator communication.** Colleagues have to communicate with
their mediator when an event ofinterest occurs. One approach is to implement
the Mediator as anObserver using the Observer (326) pattern.
Colleagueclasses act as Subjects, sending notifications to the
mediatorwhenever they change state. The mediator responds by propagating
theeffects of the change to other colleagues.
Another approach defines a specialized notification interface inMediator
that lets colleagues be more direct in their communication.Smalltalk/V for
Windows uses a form of delegation: When communicatingwith the mediator,
a colleague passes itself as an argument, allowingthe mediator to identify
the sender. The Sample Code uses thisapproach, and the Smalltalk/V
implementation is discussed further inthe Known Uses.
### Related Patterns
Facade (208) differsfrom Mediator in that it abstracts a subsystem of objects
to providea more convenient interface. Its protocol is unidirectional; thatis,
Facade objects make requests of the subsystem classes but notvice versa. In
contrast, Mediator enables cooperative behaviorthat colleague objects don't or
can't provide, and the protocol ismultidirectional.
Colleagues can communicate with the mediator using the Observer (326) pattern.
---
# 享元模式(Flyweight Pattern)
## 大話:
### 定義: 享元模式(Flyweight Pattern),運用共用技術有效地支援大量細粒度的物件。
#### 使用時機:
在享元物件內部並且不會隨環境改變而改變的共用部分,可以稱為是享元物件的內部狀態,而隨環境改變而改變的、不可以共用的狀態就是外部狀態。
享元模式可以避免大量非常相似類別的消耗。在程式設計中,有時需要產生大量細粒度的類別實體來表示資料。
如果能發現這些實體除了幾個參數外基本上都是相同的,有時就能夠大幅度地減少需要實體化的類別的數量。
如果能把那些參數移到類別實體的外面,在調用方法時將他們傳遞進來,就可以透過共用大幅度地減少單個實體的數目。
也就是說,享元模式的 Flyweight 執行時的狀態有可能是內部也有可能是外部,內部狀態儲存於 ConcreteFlyweight 物件之中,而外部物件則應該考慮由用物端物件儲存或計算,當調用 Flyweight 物件的操作時,將該狀態傳遞給它。(p.399)
(p.402)
滿足以下條件時再考慮使用
1. 使用大量物件
2. 單純被大數目的物件儲存耗費許多空間
3. 大部分物件的狀態可以被外部化
4. 若除去物件的外部狀態後發現大量的物件們可以被歸納為少數的共通物件並能夠代表。
5. 程式本身不特別依賴物件的差異性,這時就可以用 flyweight object 將元件共用,因為對應用層面來說,這些元件本身可視為無任何區別。
### Applicability
The Flyweight pattern’s effectiveness depends heavily on how and where it’s used.
Apply the Flyweight pattern when **all** of the following are true:
- An application uses a large number of objects.
- Storage costs are high because of the sheer quantity of objects.
- Most object state can be made extrinsic.
- Many groups of objects may be replaced by relatively few shared objects
once extrinsic state is removed.
- The application doesn’t depend on object identity. Since flyweight objects
may be shared, identity tests will return true for conceptually distinct
objects.
### 討論:
- 哪邊有用到呢?
- 哪邊可以用?
## GOF
### Intent
Use sharing to support large numbers of fine-grained objects efficiently.
### Also Known As
### Motivation
Some applications could benefit from using objects throughout their design, but
a naive implementation would be prohibitively expensive.
For example, most document editor implementations have text formatting and editing
facilities that are modularized to some extent. Object-oriented document editors
typically use objects to represent embedded elements like tables and figures.
However, they usually stop short of using an object for each character in the
document, even though doing so would promote flexibility at the finest levels
in the application. Characters and embedded elements could then be treated
uniformly with respect to how they are drawn and formatted. The application could
be extended to support new character sets without disturbing other functionality.
The application's object structure could mimic the document's physical structure.
The following diagram shows how a document editor can use objects to represent
characters.

The drawback of such a design is its cost. Even moderate-sized documents may require
hundreds of thousands of character objects, which will consume lots of memory
and may incur unacceptable run-time overhead. The Flyweight pattern describes
how to share objects to allow their use at fine granularities without prohibitive
cost.
A flyweight is a shared object that can be used in multiple contexts simultaneously.
The flyweight acts as an independent object in each context—it's indistinguishable
from an instance of the object that's not shared. Flyweights cannot make
assumptions about the context in which they operate. The key concept here is the
distinction between intrinsic and extrinsic state. Intrinsic state is stored in
the flyweight; it consists of information that's independent of the flyweight's
context, thereby making it sharable. Extrinsic state depends on and varies with
the flyweight's context and therefore can't be shared. Client objects are
responsible for passing extrinsic state to the flyweight when it needs it.
Flyweights model concepts or entities that are normally too plentiful to represent
with objects. For example, a document editor can create a flyweight for each letter
of the alphabet. Each flyweight stores a character code, but its coordinate
position in the document and its typographic style can be determined from the
text layout algorithms and formatting commands in effect wherever the character
appears. The character code is intrinsic state, while the other information is
extrinsic.
Logically there is an object for every occurrence of a given character in the
document:

Physically, however, there is one shared flyweight object per character, and it
appears in different contexts in the document structure. Each occurrence of a
particular character object refers to the same instance in the shared pool of
flyweight objects:

The class structure for these objects is shown next. Glyph is the abstract class
for graphical objects, some of which may be flyweights. Operations that may depend
on extrinsic state have it passed to them as a parameter. For example, Draw and
Intersects must know which context the glyph is in before they can do their job.

A flyweight representing the letter "a" only stores the corresponding character
code; it doesn't need to store its location or font. Clients supply the
context-dependent information that the flyweight needs to draw itself. For example,
a Row glyph knows where its children should draw themselves so that they are tiled
horizontally. Thus it can pass each child its location in the draw request.
Because the number of different character objects is far less than the number
of characters in the document, the total number of objects is substantially less
than what a naive implementation would use. A document in which all characters
appear in the same font and color will allocate on the order of 100 character
objects (roughly the size of the ASCII character set) regardless of the document's
length. And since most documents use no more than 10 different font-color
combinations, this number won't grow appreciably in practice. An object
abstraction thus becomes practical for individual characters.
### Applicability
The Flyweight pattern's effectiveness depends heavily on how and where it's used.
Apply the Flyweight pattern when **all** of the following are true:
- An application uses a large number of objects.
- Storage costs are high because of the sheer quantity of objects.
- Most object state can be made extrinsic.
- Many groups of objects may be replaced by relatively few shared objects
once extrinsic state is removed.
- The application doesn't depend on object identity. Since flyweight objects
may be shared, identity tests will return true for conceptually distinct
objects.
### Structure

The following object diagram shows how flyweights are shared:

### Participants
- Flyweight
- declares an interface through which flyweights can receive and act
on extrinsic state.
- ConcreteFlyweight (Character)
- implements the Flyweight interface and adds storage for intrinsic
state, if any. A ConcreteFlyweight object must be sharable. Any state
it stores must be intrinsic; that is, it must be independent of the
ConcreteFlyweight object's context.
- UnsharedConcreteFlyweight (Row, Column)
- not all Flyweight subclasses need to be shared. The Flyweight
interface enables sharing; it doesn't enforce it. It's common for
UnsharedConcreteFlyweight objects to have ConcreteFlyweight
objects as children at some level in the flyweight object structure
(as the Row and Column classes have).
- FlyweightFactory
- creates and manages flyweight objects.
- ensures that flyweights are shared properly. When a client requests
a flyweight, the FlyweightFactory object supplies an existing
instance or creates one, if none exists.
- Client
- maintains a reference to flyweight(s).
- computes or stores the extrinsic state of flyweight(s).
### Collaborations
- State that a flyweight needs to function must be characterized as either intrinsic or extrinsic. Intrinsic state is stored in the ConcreteFlyweight object; extrinsic state is stored or computed by Client objects. Clients pass this state to the flyweight when they invoke its operations.
- Clients should not instantiate ConcreteFlyweights directly. Clients must obtain ConcreteFlyweight objects exclusively from the FlyweightFactory object to ensure they are shared properly.
### Consequences
Flyweights may introduce run-time costs associated with transferring, finding,
and/or computing extrinsic state, especially if it was formerly stored as intrinsic
state. However, such costs are offset by space savings, which increase as more
flyweights are shared.
Storage savings are a function of several factors:
- the reduction in the total number of instances that comes from sharing
- the amount of intrinsic state per object
- whether extrinsic state is computed or stored.
The more flyweights are shared, the greater the storage savings. The savings
increase with the amount of shared state. The greatest savings occur when the
objects use substantial quantities of both intrinsic and extrinsic state, and
the extrinsic state can be computed rather than stored. Then you save on storage
in two ways: Sharing reduces the cost of intrinsic state, and you trade extrinsic
state for computation time.
The Flyweight pattern is often combined with the Composite (183) pattern to
represent a hierarchical structure as a graph with shared leaf nodes. A consequence
of sharing is that flyweight leaf nodes cannot store a pointer to their parent.
Rather, the parent pointer is passed to the flyweight as part of its extrinsic
state. This has a major impact on how the objects in the hierarchy communicate
with each other.
### Implementation
Consider the following issues when implementing the Flyweight pattern:
1. **Removing extrinsic state.** The pattern's applicability is determined
largely by how easy it is to identify extrinsic state and remove it from
shared objects. Removing extrinsic state won't help reduce storage costs
if there are as many different kinds of extrinsic state as there are objects
before sharing. Ideally, extrinsic state can be computed from a separate
object structure, one with far smaller storage requirements.
In our document editor, for example, we can store a map of typographic
information in a separate structure rather than store the font and type
style with each character object. The map keeps track of runs of characters
with the same typographic attributes. When a character draws itself, it
receives its typographic attributes as a side-effect of the draw traversal.
Because documents normally use just a few different fonts and styles,
storing this information externally to each character object is far more
efficient than storing it internally.
2. **Managing shared objects.** Because objects are shared, clients shouldn't
instantiate them directly. FlyweightFactory lets clients locate a
particular flyweight. FlyweightFactory objects often use an associative
store to let clients look up flyweights of interest. For example, the
flyweight factory in the document editor example can keep a table of
flyweights indexed by character codes. The manager returns the proper
flyweight given its code, creating the flyweight if it does not already
exist.
Sharability also implies some form of reference counting or garbage
collection to reclaim a flyweight's storage when it's no longer needed.
However, neither is necessary if the number of flyweights is fixed and small
(e.g., flyweights for the ASCII character set). In that case, the flyweights
are worth keeping around permanently.
### Related Patterns
The Flyweight pattern is often combined with the Composite (183) pattern to
implement a logically hierarchical structure in terms of a directed-acyclic graph
with shared leaf nodes.
It's often best to implement State (338) and Strategy (349) objects as flyweights.