Home >Java >javaTutorial >Overview of Java's 23 design patterns and 6 major design pattern principles
Generally speaking, design patterns are divided into three categories:
There are five creative patterns: factory method pattern, abstract factory pattern, singleton pattern, builder pattern, and prototype pattern.
There are seven structural modes: adapter mode, decorator mode, proxy mode, appearance mode, bridge mode, combination mode, and flyweight mode.
Behavioral patterns, eleven in total: strategy pattern, template method pattern, observer pattern, iterative sub pattern, chain of responsibility pattern, command pattern, memo pattern, state pattern, visitor pattern, mediator pattern , interpreter mode.
The details are as follows:
1. Singleton, singleton mode: ensure that a class has only one instance and provide an access method to it Global access
Point
2. Abstract Factory: Provides an interface for creating a series of related or interdependent objects,
without specifying their specific classes.
3. Factory Method: Factory method: Define an interface for creating objects and let subclasses decide which class to instantiate. Factory Method delays the instantiation of a class until the subclass kind.
4. Builder, construction mode: separates the construction of a complex object from its representation, so that the same construction process can create different representations.
5. Prototype, prototype mode: Use prototype instances to specify the types of objects to be created, and create new objects by copying these prototypes.
6. Iterator, iterator mode: Provides a method to sequentially access each element of an aggregate object without exposing the object's internal representation.
7. Observer, Observer pattern: Define one-to-many dependencies between objects. When the status of an object changes, all objects that depend on it are notified and automatically updated. .
8. Template Method: Define the skeleton of an algorithm in operation and defer some steps to subclasses. TemplateMethod allows subclasses to not change the structure of an algorithm. That is, you can redefine certain specific steps of the algorithm.
9. Command, command mode: encapsulates a request as an object, allowing you to parameterize clients with different requests, queue requests and record request logs, and Supports undoable operations.
10. State, state mode: allows an object to change its behavior when its internal state changes. The object appears to have changed its class.
11. Strategy, strategy pattern: Define a series of algorithms, encapsulate them one by one, and make them interchangeable. This pattern allows the algorithms to be independent of the users who use them. client.
12. China of Responsibility, chain of responsibility model: Give multiple objects the opportunity to process requests, thereby avoiding the coupling relationship between the sender and receiver of the request
13. Mediator, mediator pattern: Use a mediator object to encapsulate a series of object interactions.
14. Visitor, visitor mode: represents an operation that acts on each element in an object structure. It allows you to define the role without changing the class of each element. A new operation for this element.
15. Interpreter, interpreter mode: given a language, define a representation of its grammar, and define a
interpreter that uses this representation to interpret sentences in the language.
16. Memento, memo mode: Capture the internal state of an object and save this state outside the object without destroying the object.
17. Composite, combination mode: combine objects into a tree structure to represent the relationship between parts and the whole, Composite enables users to use single objects and composite objects consistently.
18. Facade, appearance mode: Provides a consistent interface for a set of interfaces in the subsystem. Fa?ade provides a high-level interface, which makes the subsystem easier to use. .
19. Proxy, proxy mode: Provide a proxy for other objects to control access to this object
20. Adapter Adapter mode: Convert one type of interface into another interface that the customer wants. The Adapter mode allows classes that cannot work together because of incompatible interfaces to work together.
21. Decrator, decoration mode: Dynamically add some additional responsibilities to an object. In terms of added functions, the Decorator mode is more flexible than generating subclasses.
22. Bridge, Bridge pattern: Separates the abstract part from its implementation part so that they can change independently.
Twenty-three, Flyweight, flyweight mode
In fact, there are two categories: concurrent mode and thread pool mode. Use a picture to describe it as a whole:
2. The six principles of design patterns
The Open Close Principle means that it is open for expansion and closed for modification. When the program needs to be expanded, the original code cannot be modified, but the original code must be expanded to achieve a hot-swappable effect. So the summary in one sentence is: in order to make the program scalable and easy to maintain and upgrade. To achieve this effect, we need to use interfaces and abstract classes, etc. We will mention this in the specific design later.
There should not be more than one reason for class changes, that is to say, each class should implement a single responsibility. If not, the class should be split.
Liskov Substitution Principle (Liskov Substitution Principle LSP) is one of the basic principles of object-oriented design-". In the Liskov Substitution Principle Say,
Anywhere a base class can appear, a subclass can definitely appear. LSP is the cornerstone of inheritance and reuse. Only when the derived class can replace the base class and the functionality of the software unit is not affected, Only the base class can be truly reused, and the derived class can also add new behaviors on the basis of the base class. The Liskov substitution principle is a supplement to the "open-closed" principle. The key steps to realize the "open-closed" principle It is abstraction. The inheritance relationship between the base class and the subclass is the specific implementation of abstraction, so the Liskov substitution principle is the specification of the specific steps to achieve abstraction. FromBaidu
Encyclopedia
In the principle of historical replacement, subclasses should try not to overwrite or overload methods of the parent class. Because the parent class represents a defined structure and interacts with the outside world through this standardized interface, subclasses should not destroy it casually.
This is the basis of the opening and closing principle. The specific content: interface-oriented programming, relying on abstraction rather than concreteness. Used when writing code When it is a concrete class, it does not interact with the concrete class, but with the upper interface of the concrete class.
This principle means: each interface There are no methods that are not used by subclasses but must be implemented. Otherwise, the interface must be split. Using multiple isolated interfaces is better than using a single interface (multiple interface methods are collected into - An interface) is better.
5. Demeter Principle (Demeter Principle)
Another expression of the least known principle is: only communicate with direct friends. As long as there is a coupling relationship between classes, it is called a friend relationship. Coupling
can be divided into dependence, association, aggregation, combination, etc. We Classes that appear in member variables, method parameters, and method return values are called direct friends. Local variables and temporary variables are not direct friends. We require unfamiliar classes not to appear as local variables in the class.
6. Composite Reuse Principle
3. Java’s 23 Design Patterns A. Creation Patterns
First of all, the simple factory pattern does not belong to the patterns involved in 23. Simple factories are generally divided into: ordinary simple factories, multi-method simple factories, and static method simple factories.
0. Simple factory mode
is to create a factory class to implement some classes that implement the same interface. Create an instance. First, look at the relationship diagram:
# Examples are as follows: (Let’s give an example of sending emails and text messages) First, create a common interface between the two:
public interface Sender { public void Send(); }
Secondly, create the implementation class:
public class MailSender implements Sender { @Override public void Send() { System.out.println("this is mailsender!"); } } public class SmsSender implements Sender { @Override public void Send() { System.out.println("this is sms sender!"); } }
Finally, build the factory class:
public class SendFactory { public Sender produce(String type){ if ("mail" .equals(type) { return new MailSender( ); }else if("sms" .equals(type)){ return new SmsSender(); }else{ System. out . println("请输入正确的类型!"); return null;) } }
Let’s test it:
public class FactoryTest { public static void main(String[] args) { SendFactory factory = new SendFactory(); Sender sender = factory.produce("sms"); sender.Send(); } }
Output: this is sms sender!
02. Multiple methods
is an improvement over the ordinary factory method pattern. In the ordinary factory method pattern, if the passed string is wrong, the object cannot be created correctly, while the multiple factory method pattern It provides multiple factory methods to create objects separately. Relationship diagram:
Modify the above code and change the SendFactory class, as follows:
public class SendFactory { public Sender produceMail(){ return new MailSender(); } public Sender produceSms(){ return new SmsSender(); } }
The test class is as follows:
public class FactoryTest{ public static void main(String[] args) { SendFactory factory = new SendFactory( ); Sender sender = factory.produceMail(); sender.Send(); } }
Output: this is mailsender!
Related articles:
Java Design Patterns - Six Principles of Design Patterns
24 Design Patterns and 7 Principles in Java
The above is the detailed content of Overview of Java's 23 design patterns and 6 major design pattern principles. For more information, please follow other related articles on the PHP Chinese website!