Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 技术 » 

Head First设计模式笔记(2)

《Head First设计模式》(深入浅出设计模式,Head First Design Patterns)是一本适合初学者学习设计模式的好书,情景丰富,简单易懂。

  1. Head First设计模式笔记(1):设计原则和模式简介
  2. Head First设计模式笔记(2):设计模式要点

设计模式(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.

上一篇: 下一篇: