Head first design patterns Reading Notes

Source: Internet
Author: User
Head first design patterns Reading Notes Luo chaohui (http://www.cnblogs.com/kesalin) This article follows the "signature-non-commercial use-consistency" creation public agreement

Finally, I am willing to finish head first design patterns. By the way, I will post my notes from my Google notebook and record them ~~

OO Basics  Abstraction, encapsulation, multi-type, inheritance

OO principles 1. encapsulation changes 2. Multi-Purpose Combination and less inheritance 3. Interface Programming, not implementation programming 4. Work hard to design loose coupling between interaction objects 5. Open for extension and disable Modification 6. Dependency inversion principle (dependency inversion principle) 7. The least knowledge principle (least knowledge) only talks with your close friend. 8. Hollywood principle: Don't call us. We will call you. 9. Single Responsibility Principle: A class should have only one cause of change.

1. encapsulation changes

-- Policy mode (encapsulate different Algorithm-- Duck example)

2. Multi-Purpose Combination and less inheritance

-- Policy mode (combination algorithm-duck example)

3. Interface Programming, not implementation programming

4. Work hard to design loose coupling between interaction objects

-- Observer mode (publisher/subscriber-weather forecast and bulletin board example)

5. Open to extensions and disable modifications

-- Decorator mode (example of coffee and spices, example of Java Io Library)

6. Dependency abstraction is required, rather than specific classes.

-- Factory method mode (pizza store and pizza example)

-- Abstract Factory model (pizza and raw material example)

7. Minimum knowledge Principle

-- Appearance mode (home theater example)

8. Hollywood principle: Don't call us. We will call you.

Under Hollywood principles, we allow underlying components to hook ourselves to the system, but high-level components determine when and how to use these underlying components. In other words, the way for high-level components to treat low-level components is "Don't call us, we will call you"

-- Template method mode (coffee and tea examples)

9. Single Responsibility Principle

-Iterator mode (different menu implementation and WAITRESS: arraylist and array)

Design Mode

Chapter 1 strategy-Rule Mode Policy mode: defines the algorithm family, which is encapsulated separately so that they can replace each other. This mode allows algorithm changes to be independent of algorithm customers.

Chapter 2 observer-Observer Mode Observer mode: defines one-to-multiple dependencies between objects. In this way, when an object changes state, all dependent objects are notified and automatically updated.

Chapter 3 decorator Mode Decorator mode definition: dynamically attaches a responsibility to an object. To expand a function, the decorator provides an alternative solution that is more flexible than inheritance. Example: starbuzz Starbucks Coffee seasoning Price Design Principle: The class should be open to expansion and closed to modification. Explanation: 1. the decorator and the object to be decorated have the same super type; 2. Since the decorator and the object to be decorated have the same super type, therefore, you can replace the original object (encapsulated) with a decorated object. 3. the decorator Can add his/her own behavior before and after the behavior of the entrusted decorator to achieve a specific purpose. 4. objects can be decorated at any time, so you can use your favorite decorator to decorate objects dynamically at runtime. Key points: -- Combination and delegation can be used to dynamically add new behaviors during motion; -- apart from inheritance, the modifier mode also allows us to expand behavior; -- the decorator Mode means a group of decorator classes that are used to wrap specific components. -- the decorator class reflects the type of the component to be decorated (in fact, they have the same type, all are implemented through interfaces or inheritance)-You can use countless Decorator Package One Components -- The decorator is generally transparent to the customer of components, unless the customer Program Depends on the specific type of the component; -- The decorator will lead to many small objects in the design. Excessive use will complicate the program.

Chapter 4 factory method-factory method mode and abstact factory method-Abstract Factory Mode The factory method mode defines an interface for creating objects, but a subclass determines which one is similar to the one to be instantiated. The factory method delays the class Instantiation to the subclass. The abstract factory mode provides an interface for creating related or dependent object families without specifying specific classes. Key Point:-All factories are used to encapsulate object creation. -A simple factory is not a real design model, but it is still a simple method that decouples customer programs from specific classes. -Factory method use inheritance: delegates the creation of an object to a subclass. The subclass implements the factory method to create an object. -Abstract factory uses Object combination: Object creation is implemented in the method exposed by the factory interface. -All factory models promote loose coupling by reducing the dependency between applications and specific classes. -The factory method allows classes to delay Instantiation to subclass. Abstract Factory creates Related Object families without relying on their specific classes. -The dependency inversion principle guides us to avoid dependency on specific types, but to rely on abstraction as much as possible. -Factory is a very powerful technique that helps us with abstract programming, rather than specific class programming.

Chapter 5 Singleton-single-piece Mode Single-piece mode-ensure that a class has only one instance and provides a global access point.

Chapter 6 command mode The command mode encapsulates requests into objects, which allows you to use different requests, queues, or log requests to parameterize other objects. The command mode also supports undo operations. Example: Remote Control

Chapter 7 adapter-adapter mode and facade-appearance Mode The adapter mode converts an interface of a class to another interface that the customer expects. The adapter allows classes that are not compatible with the original interface to work together. There are two types: Class adapter and Object Adapter. Adapter mode example: Turkey becomes duck, JDK iterator appearance mode example: Home Theater

Chapter 8 template method mode The template method Pattern Defines the skeleton of an algorithm in a method (called the template method), and delays some steps to the subclass. The template method allows subclass to redefine some steps in the algorithm without changing the algorithm structure. Hook is a method declared in an abstract class, but it only has null or default implementations. The existence of hooks allows subclasses to hook different algorithm differences. If hooks are required, the subclass determines the differences. Example: coffee and tea Key points:-The template method defines the algorithm steps and delays the implementation of these steps to subclass. -The template method provides us with Code Important techniques for reuse. -The abstract class of the template method can define specific methods, abstract methods, and hooks. -The abstract method is implemented by sub-classes. -Hook is a method. It does not do anything in an abstract class, or only does the default thing. The subclass can choose not to overwrite it. -Hollywood principles tell us to place decision-making power in high-level modules to determine how and when to call lower-level modules. -Both the policy mode and template method mode encapsulate the algorithm. One is a combination, and the other is an inheritance. -The factory method is a special version of the template method.

Chapter 9 iterator and composite-a well-managed set The iterator mode allows a method to access each element in an aggregate object sequentially without exposing its internal representation. The combination mode allows you to combine objects into a tree structure to express the "whole/part" hierarchy. The combination allows the customer to process individual objects and object combinations in a consistent manner. Example: The combination of menus and their sub-menus (tree structure) allows us to create an object structure in the tree. The tree contains combinations and individual objects. Using the combination structure, we can apply the same operation to the combination and individual objects. In other words, in most cases, we can ignore the differences between object combinations and individual objects. When to use the combination mode: When you have several object sets with a "whole/part" relationship between them and you want to treat these objects in a consistent manner, you can use the combination mode.

Chapter 10 State Mode The State mode allows an object to change its behavior when its internal state changes. The object seems to have modified its class. The State mode encapsulates the state into an independent class and delegates the action to an object that represents the current state. From the customer's perspective: if the object you use can completely change its behavior, you will think that this object is actually instantiated by another class. However, in fact, you know we use combinations to create the illusion of class changes by simply referencing different State objects. The rule mode and state mode are twins. Their class diagrams are identical, but their intentions are different. The rule mode creates a successful business around interchangeable algorithms, and the state mode helps the object control its own behavior by changing the internal state of the object. In the state mode, we encapsulate a group of behaviors in the State object, and the context behavior can be delegated to one of those State objects at any time. With the passage of time, the current State Changes in the collection of State objects to reflect the State inside the context. Therefore, the behavior of context also changes. However, the context client does not know much about the status object, or even does not even know it. Status classes increase the number of classes in the design.

Chapter 2 proxy) Proxy mode provides a replacement or placeholder for another object to control access to this object. The proxy mode is used to create a representative object, allowing the representative object to control access to an object. The objects to be proxies can be remote objects, create objects with high overhead or objects requiring security control. -Remote proxy Control Remote Object Access (RMI in Java)-virtual proxy control access creates overhead resources (Remote Image Display)-protects proxy access to resources based on permission Control

Chapter 1 compound-modes are usually used together and combined in the same design solution. -The compound mode combines two or more modes in a solution to solve common or repeated problems. Example: Duck and goose (adapter, iteration mode, observer, abstract factory, policy mode) MVC: Model View Controller (policy, observer, combination mode)

Chapter 1 patterns in real life-Let design patterns naturally appear in your design, rather than for use. -The design pattern is not a rigid dogma. You can adopt or adjust it based on your own needs. -Always use the simplest solution that meets your needs, regardless of the mode. -Learning the categories of design patterns helps you familiarize yourself with these patterns and their relationships. Pattern classification: Creation type, structure type and behavior mode Creation Mode: Abstract Factory mode, generator mode, factory method mode, prototype mode, single-piece Mode Structural Mode: Adapter mode, bridging mode, combination mode, modifier mode, appearance mode, Meta mode, proxy Mode Behavior mode: Responsibility chain mode, command mode, interpreter mode, iterator mode, intermediary mode, memo mode, observer mode, state mode, policy mode, template method mode, and visitor Mode Class Mode and Object Mode Class Mode: Template Method, factory method, adapter, and interpreter) Object Mode: Combination Mode (), visitor mode, appearance mode, proxy mode, policy mode, bridging mode, metadata mode, abstract factory mode, single-piece mode, iterator mode, command mode, memorandum mode, observer mode, responsibility chain mode, intermediary mode, prototype mode, generator Mode Summary: Modifier mode: Wrap an object to provide new behavior. Adapter mode: encapsulate objects and provide different interfaces. Template Method mode: The subclass determines how to implement the steps in an algorithm. Factory method mode: The subclass determines which method to create is similar. Single-piece mode: ensure that only one object is created. Rule mode: encapsulate interchangeable behaviors and use delegation to determine which behavior to use. Combination Mode: the customer processes object sets and individual objects in a consistent manner. Status mode: encapsulates status-based behaviors and uses delegation to switch between actions. Iterator mode: Walk in the object set, rather than exposing the implementation of the Set. Appearance mode: simplifies the interfaces of a group of classes. Modifier mode: Wrap an object to provide new behavior. Abstract Factory method: allows customers to create object families without specifying their specific classes. Observer mode: enables the object to be notified when the state changes. Proxy mode: Wrap an object to control access to this object. Command mode: encapsulate requests into objects.

Remaining modes in Appendix

Bridge) Using the bridge mode not only changes your implementation, but also changes your abstraction. The bridge mode puts implementation and abstraction in two different class layers so that they can be changed independently. Advantages of bridging:-decoupling is implemented so that it is no longer permanently bound to the interface. -Abstraction and implementation can be expanded independently without affecting the other party. -Changes made to the "Specific abstract class" will not affect the customer. Purpose and disadvantage of bridging:-applicable to graphics and window systems that need to span multiple platforms. -When you need to change the interface and its implementation in different ways, you will find that the bridge mode is very useful. -The disadvantage of the bridge mode is that it increases complexity. Example: Abstraction of controllers and interfaces Builder Mode) -Encapsulate the construction process of a product in generator mode and allow step-by-step construction. Advantages of the generator:-encapsulate the creation process of a complex object. -Allow objects to be created in multiple steps and change the process (this is different from the engineering mode with only one step ). -Hide the internal implementation of the product from the customer. -The product implementation can be replaced because the customer only sees one abstract interface. Generator's purpose and Disadvantages:-often used to create a composite structure-customers who use the generator mode to create objects need to have more domain knowledge than the factory mode. Example: vacation plan Chain of responsibility) When you want more than one object to have the opportunity to process a request, you can use the responsibility chain mode. Advantages of the responsibility chain model:-decoupling request senders and receivers-can simplify your objects, because it does not need to know the structure of the chain-by changing the members in the chain or mobilizing their order, you can dynamically add or delete the purpose and disadvantages of the responsible chain: -It is often used in window systems to process events such as the mouse and keyboard-it is not guaranteed that the request will be executed; if no object is processed, it may fall beyond the end of the chain (this can be an advantage or a disadvantage)-it may not be easy to observe the characteristics of the runtime, which hinders the debugging example: Different emails (SPAM, fans emails, customer service emails, business emails, etc.) Flyweight) If you want an instance of a class to be used to provide many "virtual instances", you can enjoy the advantages of the metadata mode:-Reduce the number of object instances in the runtime, memory saving-the usage and disadvantages of the shared element mode are centrally managed by the status of many "virtual objects":-when a class has many instances and these instances can be controlled by the same method, we can use the metadata-disadvantage: Once you implement it, a single logical instance cannot have an independent and different example of the metadata processing mode: display of embellishment trees in Landscape Design (only one tree instance, sharing location annual ring information) Advantages of the interpreter mode (intepreter) the interpreter mode for language creation Interpreter:
-Each syntax rule is represented as a class to facilitate language implementation-because the syntax is represented by many classes, therefore, you can easily change or extend the language. By adding new methods to the class structure, you can add new behaviors while interpreting them, for example, print formatting or perform complex program verification to explain the purpose and disadvantages:-when you need to implement a simple language, use the interpreter-when you have a simple syntax that is more important than efficiency, use the interpreter-to process the script language and Programming Language -When the number of language rules is too large, this mode may become quite complicated. In this case, the interpreter/compiler generator may be more suitable for example: duck Pond language interpreter for controlling ducks Mediator) The intermediary mode is used to centralize the complex communication and control methods between related objects. Each object tells the intermediary when its status changes. Each object responds to the request sent by the intermediary. The intermediary contains the control logic of the entire system. When an object requires a new rule, or a new object is added to the system, all the logic that needs to be used is also added to the intermediary. Advantages of the intermediary mode:-by decoupling objects from each other, the reusability of objects can be increased-by centralizing the control logic, system maintenance can be simplified-the message passing between objects can be simplified and the purpose and disadvantages of the intermediary mode can be greatly reduced: -The intermediary mode is often used to coordinate related GUI components. The disadvantage of the intermediary mode is that, if it is not properly designed, the intermediary object itself will become too complex. Example: Living automation (alarm, coffee, calendar, sprinkler) Memento) When you need to let the object return the previous State (for example, undo), the memorandum mode is used. The memorandum mode has two goals: to store the important status of key objects in the system and to maintain the encapsulation of key objects. Do not forget the single responsibility principle, and do not mix the work that maintains state with key objects. This is better. This object is called a memorandum. Advantages of the memorandum mode:-The stored state should be put out and not mixed with key objects, this helps maintain cohesion-maintain the data encapsulation of joint objects-provides an easy-to-achieve recovery capability memorandum mode of purpose and Disadvantage:-Memorandum used for storage status-disadvantages of using memos: the process of storing and restoring the State may be quite time-in Java systems, you can actually consider using the serialization mechanism to store the State example of the system: the storage progress function in the game Prototype) The prototype mode is used when the process of creating an instance of a given class is expensive or complex. Prototype mode allows you to create a new instance by copying an existing instance (in Java, this usually means using the clone () method or deserialization ). The focus of this model is that the customer's code can create new instances without knowing the specific classes to be instantiated. Advantages of the prototype:-hide the complexity of creating new instances to the customer-provide options for the customer to generate unknown objects-in some environments, the purpose and disadvantage of copying an object is more effective than creating a new object in the prototype mode:-in a complex class hierarchy, when the system must create a new object from many of the types, prototype-disadvantage: copying objects is sometimes quite complex. Example: creating various monsters in a game Visitor mode (visitor) When you want to add new capabilities to a combination of objects, and encapsulation is not important, use the visitor mode. The customer asks the visitor to obtain information from the combination structure. The new method can be added to the visitor without affecting the combination. The visitor must be able to call the getstate () of the combination class (), this is exactly where you can add new methods for customers to use. All the things required for these composite classes are to add a getstate () method without worrying about exposing themselves. Advantages of the visitor mode:-allows you to add new operations to the composite structure without changing the structure itself-it is relatively easy to add new operations-operations performed by visitors, the Code is the purpose and disadvantage of the centralized visitor mode:-when the visitor mode is adopted, the encapsulation of the combination class will be broken-because the wandering function involves, therefore, it is more difficult to change the combination structure. For example, add nutrients to the menu of the country restaurant and display the energy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.