Design patterns notes - structured

Adapter (Adapter)

The interface of a class into another interface clients expect. Adapter pattern makes the original and not because of incompatible interfaces to work with those classes can work together. In "Design Patterns" book will be divided into two categories adapter adapter mode model and the object adapter pattern. Except that the adapter is fit for the role of the role of adaptation is done through inheritance or through a combination of completion. Because Java does not support multiple inheritance, encapsulation and inheritance are suspected of sabotage, so this combination instead of using inheritance. The model contains the following components:

  • Target (Target) Role: Define Client-use interface.
  • Be fit (Adaptee) Role: This role has an existing and used interface, and this interface is we need to fit in.
  • Adapter (Adapter) Role: This is the core of the adapter mode. It will be fit into the role of the interface has been the role of hope goal of the interface.

The following categories do we TextCircle adapter so that it can meet the client's Circle interfaces.

class Circle extends Shape {
    // Here reference  TextCircle
    private TextCircle tc;
    public Circle() {
        tc = new TextCircle(); // Initialization
    void public display() {
        tc.displayIt(); // The method inside the original method call TextCircle

The model and the agency model agency model the main difference is that the application is to change the interface, not named, but is there a control interface functions. The Adapter Interface Converter is emphasized.

Off-topic: In Java, there is something called a "default adapter mode" applications, we are talking about it and the adapter model is fully two things. The default mode is an interface adapter provides the default implementation, this subtype can be fit from the default mode for extended, to avoid the extension from the original interface to realize when they do not care about some of the interface.

Bridge Mode (Bridge)

GOF in the "design mode" giving the bridge model is defined as: the abstract part and it is the realization of partial separation, so that they All can vary independently. Here's the abstract part and the part is not that we usually realize that the parent and child classes, interfaces and implementation classes, but by combination relations. In other words, to achieve some abstract part of the call was to be used to complete the abstract part of the function.

In short, you can analyze the types of changes, will change the framework of the use of abstract class definition out, and then change the contents of the use of specific sub-classes were realized.
Also, if the specific implementation, there is almost duplicate the functions of the code, will be extracted from these acts, but also provide them with the interface and then the combination of the service provided to the original sub-categories. This reached the abstract part of the changes and achieve some independence, but also to achieve some of the reuse. The pattern formed by the following roles:

  • Abstract (Abstraction) role: it defines the interface and abstract class maintains a pointer to the realization (Implementor) a reference to the role.
  • Precise abstract (RefinedAbstraction) Role: Implementation and expansion of the role defined by the abstract interface.
  • Implementation (Implementor) Role: interface implementation class is given, where the role of interfaces and abstract the interface can be inconsistent.
  • Realization (ConcreteImplementor) role: the role given to achieve the definition of interface implementation.

The following code from the "Thinking in Patterns with Java":

// The abstract part of abstract roles
class Abstraction {
    // Maintains a link to implementation  (Implementor) Role of reference
    private Implementation implementation;
    public Abstraction(Implementation imp) {
        implementation = imp;
    // The following defines the abstract section should have the interface
    public void service1() {
        // Use the implementation part of the existing interface
        // Combination of implementation capability
    public void service2() {

// The abstract part of accurate abstract roles
class ClientService1 extends Abstraction {
    public ClientService1(Implementation imp) { super(imp); }
    // Use the abstract roles provides methods combined to complete a function
    // This is why call precise abstract roles  ( Fixed abstract roles  )
    public void serviceA() {
    public void serviceB() {

// Implementation of part of the implementation of role
interface Implementation {
    // This interface simply defines a certain interface
    void facility1();
    void facility2();
    void facility3();
    void facility4();

// The specific implementation role is to implement the role interface to implement and complete certain functions
class Implementation1 implements Implementation {
    // Has been omitted

Usage scenario:

  1. When you have multiple parts of the system to use to similar behavior, or a combination of many similar acts, you can consider using the bridge mode to increase reuse, and reduce the differences arise because the behavior of sub-categories.
  2. System, the behavior of a class may have several different trends, to be effective to change package, consider the behavior of the class drawn.
  3. Of course, the above situation can be so similar behavior may have to be different class to use, you can also consider using the bridge mode to achieve.

Combination mode (Composite)

The object tree structure to organize themselves in order to reach "part - whole" hierarchical structure, making the client portfolio on a single object and consistent use of the object. Definition can be used from the combination mode of the environment: in the design of the object to that "part - whole" hierarchy, want the user to ignore the combination of the different objects with a single object, and consistent use of composite structure in all objects. It consists of:

  • Abstract component role (Component): It is the object of a statement for the portfolio interface can also be the default behavior for the total interface.
  • Foliage component role (Leaf): the leaf nodes in the portfolio that target - no child nodes, the role of a statement to achieve abstract component interface.
  • Branch component role (Composite): In combination, said branch node objects - have child nodes, the role of the statement to achieve abstract component interfaces, storage sub-components.

Specific examples may refer to JUnit's TestCase and TestSuite achieve.

Decorative patterns (Decorator)

Decorative pattern, also known as packing mode (Wrapper), GOF in "design mode", a book given is defined as: an object dynamically to add some additional functions. To increase the functionality is, Decorator pattern is more flexible than subclassing. It consists of:

  • Abstract component role (Component): defines an abstract interface to standard object ready to receive additional responsibilities.
  • The role of specific components (Concrete Component): This is to be trimmed, define a function that will be decorated to increase the class.
  • Decorative role (Decorator): holds an instance of a component object, and defines the abstract component interface definitions.
  • Concrete decorative role (Concrete Decorator): responsible for adding additional functionality to the component.

The following to JUnit, for example, used to extend TestCase decorated model:

// This is the abstract widget roles
public interface Test {
    public abstract int countTestCases();
    public abstract void run(TestResult result);

// Specific Widget objects, but there is an abstract class
public abstract class TestCase extends Assert implements Test {
    public int countTestCases() {
        return 1;
    public TestResult run() {
        TestResult result = createResult();
        return result;
    public void run(TestResult result) {;

// Decorative role
public class TestDecorator extends Assert implements Test {
    // Here in accordance with the above requirements, retain an instance of the Widget object
    protected Test fTest;
    public TestDecorator(Test test) {
        fTest= test;
    public void basicRun(TestResult result) {;
    public int countTestCases() {
        return fTest.countTestCases();
    public void run(TestResult result) {

// The specific role, this type of decorative effect is to set the number of executions of the test class
public class RepeatedTest extends TestDecorator {
    private int fTimesRepeat;
    public RepeatedTest(Test test, int repeat) {
        if (repeat < 0)
            throw new IllegalArgumentException("Repetition count must be > 0");
        fTimesRepeat= repeat;
    // See how decoration!
    public int countTestCases() {
        return super.countTestCases() * fTimesRepeat;
    public void run(TestResult result) {
        for (int i= 0; i < fTimesRepeat; i++) {
            if (result.shouldStop()) break;

// Use of the time, you can use the following method
TestDecorator test = new RepeatedTest(new TestXXX() , 3);

Off-topic: in, the example is not purely decorative pattern, which is the decorative pattern, adapter pattern of mixed use.

Facade pattern (Facade)

Facade pattern, also known as the appearance model. GOF in the "Design Patterns" book gives the following definition: a group for the subsystem interface to provide a consistent interface, Facade defines a high-level interface that makes the subsystem easier to use. The pattern formed by the three roles:

  • Facade role (facade): This is the facade pattern core. It is the role of customer calls, so it familiar with the sub-system. It is the role of internal customer needs have been scheduled several feature combinations.
  • Subsystem role: to achieve a sub-system. It is concerned, facade and customer roles on the same role is unknown, it has no facade role of information and links.
  • Client role: the role of call facade to get the function to complete.

Use of the environment:

  1. For a complex subsystem provides a simple interface.
  2. Client and the realization of some abstract class there is a considerable dependence between. Facade into this subsystem and other subsystems with separate customers can improve the independence and portability subsystem.
  3. When you need to build a hierarchy of subsystems, use the facade pattern defines the entry point on each subsystem. If the subsystems are interdependent, you can allow them to communicate only through the facade to simplify the dependencies between them.

A typical application of the model is the database connection. Generally the database each time we visit, we must undertake the following:

  1. Connect the first instance be
  2. Then open the connect get connected, get a statement
  3. Implementation of the sql statement to query, get the query result set.

We can extract these steps, encapsulated in a class inside. In this way, each database access only to the implementation of the necessary parameters to this class on it.

Flyweight Pattern (Flyweight)

Using a shared class to avoid the large with the same content "categories" of money. This cost the most common is to increase the visual impact of memory loss. Flyweight pattern to share effective ways to support a large number of fine-grained objects, reducing overhead.

Between things are different, but then there are some similarities, if only to share the exact same thing, then the Flyweight pattern can be said is not feasible. Therefore, we should try to share things in common, yet retains its individuality. To achieve this, Flyweight pattern to distinguish the internal state (intrinsic) and external conditions (extrinsic). Internal state is common, is the personality of the external state. Flyweight internal state stored in the internal, not with the different changes in the environment, can be shared. External state is not shared, it is changed with the environment, and therefore outside the state is by the client to maintain. In each specific environment, the client will enjoy the element passed to the external state to create different objects out.

Simple Flyweight Pattern

  • Abstract Flyweight role: the role of specific Flyweight provides must implement the method, while the external parameters in the form of state is to pass through this method. In Java, can be abstract classes, interfaces to play.
  • Flyweight specific role: the role of requirements to achieve an abstract way. If there is an internal state, it is responsible for the internal state to provide storage space.
  • Flyweight Factory Role: responsible for creating and managing Flyweight role. To achieve the shared objective, the realization of this role is the key!
  • Client role: to maintain all the Flyweight object reference, but also the need to store the corresponding external state.

Composite Flyweight Pattern

  • Abstract Flyweight role: the role of specific Flyweight provides must implement the method, while the external parameters in the form of state is to pass through this method. In Java, can be abstract classes, interfaces to play.
  • Flyweight specific role: the role of requirements to achieve an abstract way. If there is an internal state, it is responsible for the internal state to provide storage space.
  • Composite Flyweight role: it represents the object is not shared, and can be decomposed into multiple simple Flyweight object combination.
  • Flyweight Factory Role: responsible for creating and managing Flyweight role. To achieve the shared objective, the realization of this role is the key!
  • Client role: to maintain all the Flyweight object reference, but also the need to store the corresponding external state.

Flyweight Pattern composite mix of uses - for the role of specific Flyweight and Flyweight composite role and handle the same. It also determines the role of composite Flyweight contains simple Flyweight each have the same external conditions, and these simple Flyweight internal state can be different.

Java to enjoy the longest element pattern is seen in String, in Java, will maintain a String Pool, for the string object that can be shared, will first look in the String Pool in the existence of the same String content (the same characters), If there is a direct return on, and not directly create a new String object, to reduce memory consumption.

Off-topic: the external and internal state to maintain the correspondence between the state, in the lookup, GOF book using BTree structure, as to find time to spend, so it is also pointed out that the use of the Flyweight pattern to pay the price: the time for space. Information on how to design the external state structures to make search time, which is another important issue.

Agent model (Proxy)

Provide a proxy for other objects to control access to this object. According to "Java and the Model" book on the proxy pattern classification, agent model is divided into eight kinds, here will be some common and important are listed below:

  • Remote (Remote) proxy: a different address space in a local representative of the target object. For example: you can one in a corner of the world a false impression of the machine through a proxy as part of your LAN.
  • Virtual (Virtual) Agent: According to the consumption of resources need to be a lot more complex objects or delayed when the real need to create. For example: If a large image, takes a long time to show up, then when the image contained in the document, use the editor or browser to open this document, this may affect the big picture to read the document, which Proxy need to be a picture instead of the real picture.
  • Protection (Protect or Access) Agent: Controlling access to an object. For example: In the forum, the different identities landing, with different permissions, permission to use proxy mode control (of course, can also be achieved using other methods).
  • Intelligent quote (Smart Reference) Agent: provides the target object than the additional services. For example: access to the flow record (this is a relatively simple example), provide some Tips, etc..

Agent model in the "agent" To realize the agency mission, it must be agents of "manufacturers" use a common interface, so the role of agent model, there are three form:

  • Abstract thematic roles: theme and proxy statement of the real theme of the common interfaces.
  • Agency thematic roles: Internal contain a reference to the real subject, and the role of providing and reality theme the same interface.
  • Real thematic roles: the definition of real objects.

The following have been registered with the forum permissions for different users and visitors as an example.

// First we implement an abstract theme role  MyForum
public interface MyForum {
    public void AddFile();

// Real theme role
public class RealMyForum implements MyForum {
    public void AddFile() {
        // Implementation of specific method

// Agent theme role
public class MyForumProxy implements MyForum {
    private RealMyForum forum = new RealMyForum();
    private int permission; // Permission value  

    public MyForumProxy(int permission) {
        this.permission = permission;
    // Implementation of the interface
    public void AddFile() {
        // Meet the permission set should only be able to perform the operation
        //Constants  Is a constant class
        if (Constants.ASSOCIATOR == permission) {
        } else
            System.out.println("You are not a associator of MyForum!");
分类:Java 时间:2010-03-28 人气:317
blog comments powered by Disqus


iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.239 (s). 12 q(s)