2004-11-24
Prototype Mode
Name: Prototype,
Problem:
Assume that you want to create a curve editor with graphic representation. A graphic is used to represent break breaks and notes. a selection panel controls and selects music objects. For example, you can select a break on the panel, placed on the Five-line spectrum. We defined the abstract graphics class for the music elements of the Five-line spectrum, defined the abstract tool class for the panel, and designed the graphicstool class for adding some graphic tools to the five-line spectrum.
The problem is that the graphics class does not know how to create a five-line spectrum instance and add it to the music score. If you create a graphictool class for each music object class, a large number of child classes will be generated (unrealistic ). In fact, our subclass can be modified on another class to meet the requirements.
Solution:
Let the graphicstool class generate a new object based on the original class (prototype) by copying garphics, clone it and add the prototype to the document as the parameter. Each graphics subclass supports a clone operation. Therefore, the graphicstool class supports creating all graphics subclasses.
Effect:
Reduces the number of product object classes. You can add or delete products at runtime.
Effectively defines the behavior of the new class, which can be achieved through the clone operation. Classes can be dynamically loaded in some environments.
Disadvantage: each class should consider how to implement the clone operation, involving superficial and complex cloning.
Figure:
Singleton Mode
Name: Also known as single-piece Mode
Problem:
In many cases, we need to ensure that only one object of a certain type is available in the application. For example, in the print offline system, we submit a print task to the offline system, instead of waiting in queue for each print object.
How can we ensure that there is only one instance and it is easy to access?
Solution:
A constructor is a protected constructor without any constructor parameters.
Defines a static member (equivalent to a global variable) to save the single-piece mode object. Define a static method, such as getinstance, which returns a unique instance. This method first checks whether a static member is directed to an instance. If not, it calls the protection structure to generate a static member. Otherwise, the static member is directly returned.
Effect:
At any time, you can ensure that you get an instance and only a single instance.
Figure:
The above five creation modes provide flexible object creation and flexible object requirements.