《Head First设计模式》（深入浅出设计模式，Head First Design Patterns）是一本适合初学者学习设计模式的好书，情景丰富，简单易懂。
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Knowing the OO basics does not make you a good OO designer.
Good OO designs are reusable, extensible and maintainable.
Patterns show you how to build systems with good OO design qualities.
Patterns are proven objectoriented experience.
Patterns don’t give you code, they give you general solutions to design problems. You apply them to your specific application.
Patterns aren’t invented, they are discovered.
Most patterns and principles address issues of change in software.
Most patterns allow some part of a system to vary independently of all other parts.
We often try to take what varies in a system and encapsulate it.
Patterns provide a shared language that can maximize the value of your communication with other developers.
The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.
The subject and observers define the one-to-many relationship. The observers are dependent on the subject such that when the subject’s state changes, the observers get notified. Depending on the style of notification, the observer may also be updated with new values.
The Observer Pattern defines a one-to-many relationship between objects.
Subjects, or as we also know them, Observables, update Observers using a common interface.
Observers are loosely coupled in that the Observable knows nothing about them, other than that they implement the Observer Interface.
You can push or pull data from the Observable when using the pattern (pull is considered more “correct”).
Don’t depend on a specific order of notification for your Observers.
Java has several implementations of the Observer Pattern, including the general purpose java.util.Observable.
Watch out for issues with the java.util.Observable implementation.
Don’t be afraid to create your own Observable implementation if needed.
Swing makes heavy use of the Observer Pattern, as do many GUI frameworks.
You’ll also find the pattern in many other places, including JavaBeans and RMI.
The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a fl exible alternative to subclassing for extending functionality.
Inheritance is one form of extension, but not necessarily the best way to achieve flexibility in our designs.
In our designs we should allow behavior to be extended without the need to modify existing code.
Composition and delegation can often be used to add new behaviors at runtime.
The Decorator Pattern provides an alternative to subclassing for extending behavior.
The Decorator Pattern involves a set of decorator classes that are used to wrap concrete components.
Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)
Decorators change the behavior of their components by adding new functionality before and/or after (or even in place of) method calls to the component.
You can wrap a component with any number of decorators.
Decorators are typically transparent to the client of the component; that is, unless the client is relying on the component’s concrete type.
Decorators can result in many small objects in our design, and overuse can be complex.
The Factory Method Pattern defi nes an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
All factories encapsulate object creation.
Simple Factory, while not a bona fide design pattern, is a simple way to decouple your clients from concrete classes.
Factory Method relies on inheritance: object creation is delegated to subclasses which implement the factory method to create objects.
Abstract Factory relies on object composition: object creation is implemented in methods exposed in the factory interface.
All factory patterns promote loose coupling by reducing the dependency of your application on concrete classes.
The intent of Factory Method is to allow a class to defer instantiation to its subclasses.
The intent of Abstract Factory is to create families of related objects without having to depend on their concrete classes.
The Dependency Inversion Principle guides us to avoid dependencies on concrete types and to strive for abstractions.
Factories are a powerful technique for coding to abstractions, not concrete classes.
The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.
The Singleton Pattern ensures you have at most one instance of a class in your application.
The Singleton Pattern also provides a global access point to that instance.
Java’s implementation of the Singleton Pattern makes use of a private constructor, a static method combined with a static variable.
Examine your performance and resource constraints and carefully choose an appropriate Singleton implementation for multithreaded applications (and we should consider all applications multithreaded!).
Beware of the double-checked locking implementation; it is not thread-safe in versions before Java 2, version 5.
Be careful if you are using multiple class loaders; this could defeat the Singleton implementation and result in multiple instances.
If you are using a JVM earlier than 1.2, you’ll need to create a registry of Singletons to defeat the garbage collector.
The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.
The Command Pattern decouples an object, making a request from the one that knows how to perform it.
A Command object is at the center of this decoupling and encapsulates a receiver with an action (or set of actions).
An invoker makes a request of a Command object by calling its execute() method, which invokes those actions on the receiver.
Invokers can be parameterized with Commands, even dynamically at runtime.
Commands may support undo by implementing an undo method that restores the object to its previous state before the execute() method was last called.
Macro Commands are a simple extension of Command that allow multiple commands to be invoked. Likewise, Macro Commands can easily support undo().
In practice, it is not uncommon for “smart” Command objects to implement the request themselves rather than delegating to a receiver.
Commands may also be used to implement logging and transactional systems.
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
The Facade Pattern provides a unifi ed interface to a set of interfaces in a subsytem. Facade defi nes a higherlevel interface that makes the subsystem easier to use.
When you need to use an existing class and its interface is not the one you need, use an adapter.
When you need to simplify and unify a large interface or complex set of interfaces, use a facade.
An adapter changes an interface into one a client expects.
A facade decouples a client from a complex subsystem.
Implementing an adapter may require little work or a great deal of work depending on the size and complexity of the target interface.
Implementing a facade requires that we compose the facade with its subsystem and use delegation to perform the work of the facade.
There are two forms of the Adapter Pattern: object and class adapters. Class adapters require multiple inheritance.
You can implement more than one facade for a subsystem.
An adapter wraps an object to change its interface, a decorator wraps an object to add new behaviors and responsibilities, and a facade “wraps” a set of objects to simplify.
The Template Method Pattern defi nes the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefi ne certain steps of an algorithm without changing the algorithm’s structure.
A “template method” defines the steps of an algorithm, deferring to subclasses for the implementation of those steps.
The Template Method Pattern gives us an important technique for code reuse.
The template method’s abstract class may define concrete methods, abstract methods and hooks.
Abstract methods are implemented by subclasses.
Hooks are methods that do nothing or default behavior in the abstract class, but may be overridden in the subclass.
To prevent subclasses from changing the algorithm in the template method, declare the template method as final.
The Hollywood Principle guides us to put decision-making in high-level modules that can decide how and when to call low level modules.
You’ll see lots of uses of the Template Method Pattern in real world code, but don’t expect it all (like any pattern) to be designed “by the book.”
The Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition.
The Factory Method is a specialization of Template Method.
The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
An Iterator allows access to an aggregate’s elements without exposing its internal structure.
An Iterator takes the job of iterating over an aggregate and encapsulates it in another object.
When using an Iterator, we relieve the aggregate of the responsibility of supporting operations for traversing its data.
An Iterator provides a common interface for traversing the items of an aggregate, allowing you to use polymorphism when writing code that makes use of the items of the aggregate.
We should strive to assign only one responsibility to each class.
The Composite Pattern provides a structure to hold both individual objects and composites.
The Composite Pattern allows clients to treat composites and individual objects uniformly.
A Component is any object in a Composite structure. Components may be other composites or leaf nodes.
There are many design tradeoffs in implementing Composite. You need to balance transparency and safety with your needs.
The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
The State Pattern allows an object to have many different behaviors that are based on its internal state.
Unlike a procedural state machine, the State Pattern represents state as a full-blown class.
The Context gets its behavior by delegating to the current state object it is composed with.
By encapsulating each state into a class, we localize any changes that will need to be made.
The State and Strategy Patterns have the same class diagram, but they differ in intent.
Strategy Pattern typically configures Context classes with a behavior or algorithm.
State Pattern allows a Context to change its behavior as the state of the Context changes.
State transitions can be controlled by the State classes or by the Context classes.
Using the State Pattern will typically result in a greater number of classes in your design.
State classes may be shared among Context instances.
The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.
The Proxy Pattern provides a representative for another object in order to control the client’s access to it. There are a number of ways it can manage that access.
A Remote Proxy manages interaction between a client and a remote object.
A Virtual Proxy controls access to an object that is expensive to instantiate.
A Protection Proxy controls access to the methods of an object based on the caller.
Many other variants of the Proxy Pattern exist including caching proxies, synchronization proxies, firewall proxies, copy-on-write proxies, and so on.
Proxy is structurally similar to Decorator, but the two differ in their purpose.
The Decorator Pattern adds behavior to an object, while a Proxy controls access.
Java’s built-in support for Proxy can build a dynamic proxy class on demand and dispatch all calls on it to a handler of your choosing.
Like any wrapper, proxies will increase the number of classes and objects in your designs.
A Compound Pattern combines two or more patterns into a solution that solves a recurring or general problem.
The Model View Controller Pattern (MVC) is a compound pattern consisting of the Observer, Strategy and Composite patterns.
The model makes use of the Observer Pattern so that it can keep observers updated yet stay decoupled from them.
The controller is the strategy for the view. The view can use different implementations of the controller to get different behavior.
The view uses the Composite Pattern to implement the user interface, which usually consists of nested components like panels, frames and buttons.
These patterns work together to decouple the three players in the MVC model, which keeps designs clear and flexible.
The Adapter Pattern can be used to adapt a new model to an existing view and controller.
Model 2 is an adaptation of MVC for web applications.
In Model 2, the controller is implemented as a servlet and JSP & HTML implement the view.