Design principles and modes

Source: Internet
Author: User
Article structure:1. Preface2. Design Principles3. Design Mode3.1 create Mode3.2 structured Mode3.3 behavior mode Preface

Design principles and patterns are designed to help us design reusable, scalable, and maintainable applications.

Design principles: guidelines for designing or restructuring the system.

Design Pattern: an effective method to solve certain problems.

The design principle and design pattern should achieve the goal of: when the demand changes or the system upgrades, as little as possible to change the code, as much as possible to implement new functions.

The design principle is the "story behind" the design pattern. to deeply understand the design pattern, we must first thoroughly understand the design principles.

 

Design principles

1. Open Close Principle)

Open for extension, closed for modifications.

It is open to extensions and closed to modifications.

It can be said that the principle of open/closed is the core principle of all principles, and its definition is the best explanation of scalability and maintainability.

2. Dependency inversion principle (dependency inversion principle)

Depend upon events actions. Don't depend upon concretions.

The dependency inversion principle emphasizes interface-oriented programming, and relies on abstraction rather than specifics. The dependency inversion principle and the open/closed principle are inherently the same. One emphasizes extension, and the other is the most commonly used mechanism for extension.

3. Interface segregation principle)

Specified client-specific interfaces are better than one general-purpose interface.

The interface isolation principle emphasizes that an interface corresponds to one customer, so that one interface is not provided to multiple customers. an interface corresponds to a customer. When the customer's needs change, only the corresponding interface needs to be changed. it embodies the idea of High Cohesion and low coupling.

4. Single Responsibility Principle)

A class shoshould have only one reason to change.

For a class, there should be only one reason for his change.

That is to say, do not put different responsibilities for different reasons of change together, because different changes will affect irrelevant responsibilities. A class has a single function as much as possible. A single function does not mean that we cannot implement more than one function. It is for later testing and maintenance. Each class is very single and we can implement it in one step when looking for errors. when adding new functions, you do not need to involve many classes.

5. liskov's substitution principle)

Derived types must be completely substitutable for their base types.

Child types must be able to replace their parent types. This principle is a constraint on inheritance. The lean replacement principle is well understood. For example, the MySQL Java driver must comply with the JDBC specification.

Reference a very good summary:The principle of opening and closing is the general principle,It tells us that it is open to expansion.,Disable Modification;The dependency inversion principle tells us that interface-oriented programming is required.;The interface isolation principle tells us to simplify and simplify the interface design;The single responsibility principle tells us that the implementation class should have a single responsibility;The Lee replacement principle tells us not to break down the inheritance system.

In actual development, we should try our best to achieve these principles, rather than follow these principles at any time. any Java program violates these guidelines. the use of principles at the right time can make our programs more flexible, but rigid and stubborn application of these principles will make the program more complex and easier.

 

Design Mode

Gof divides 23 design patterns into three types: creation, structure, and behavior. the following lists some common modes and their application instances. the implementation of the model instance mentioned below is different from that in books. Compared with the implementation of the model, I pay more attention to the application scenarios of the model.

Creation Mode

Singleton Mode(Singleton): Ensure that there is only one instance for a class in the program.

Application Example: Java. Lang. runtime in JDK

Public class runtime {/*** class initialization instance when loading */Private Static runtime currentruntime = new Runtime (); /*** provides methods for obtaining instances */public static runtime getruntime () {return currentruntime;}/** privatized constructor */private Runtime () {} // remaining Methods
View code

Factory Model(Factory/abstract factory pattern): Used to encapsulate object Creation

Factory method mode: defines an interface for object creation, but the subclass determines which class to instantiate.

Abstract Factory mode: provides an interface for creating families of related or dependent objects without specifying specific classes.

I personally feel that the factory method mode has the same purpose as the abstract factory mode, but its forms are different. I do not like to distinguish them conceptually. java. util. the calendar class is a typical application of the factory model:

Public static calendar getinstance (timezone zone, locale alocale) {return createcalendar (zone, alocale);} Private Static calendar createcalendar (timezone zone, locale alocale) {calendar Cal = NULL; string caltype = alocale. getunicodelocaletype ("ca");/** create different objects based on different conditions. Typical factory mode application scenarios **/If (caltype = NULL) {If ("th ". equals (alocale. getlanguage () & ("th ". equals (alocale. getcountry () {Cal = new buddhistcalendar (zone, alocale);} else {Cal = new gregoriancalendar (zone, alocale);} else if (caltype. equals ("Japanese") {Cal = new japaneseimperialcalendar (zone, alocale);} else if (caltype. equals ("Buddhist") {Cal = new buddhistcalendar (zone, alocale);} else {Cal = new gregoriancalendar (zone, alocale);} return Cal ;}
View code

Factory is a very powerful technique that can help us with abstract programming, rather than specific class programming.

Prototype(Prototype): Specify the type of the object to be created by providing a prototype object, and then create more objects of the same type by copying the prototype object.

Application Example: There are many classes that implement prototype in JDK. All classes that implement the java. Lang. cloneable interface implement prototype.

Builder Mode(Builder): Encapsulate the creation process of complex objects.

Application Scenario: When the algorithms for creating complex objects are independent of the components of the objects and their assembly methods, the construction process must allow different representations of the objects to be constructed.

Application Example: Java. Lang. stringbuffer, java. Lang. stringbuilder

 

Structure Mode

Adapter Mode(Adapter):Converts an interface of a class to another interface that the customer expects. The adapter allows the incompatible classes to work together.

Application Example: Java. Io. inputstreamreader and Java. Io. outputstreamwriter in JDK

Decoration Mode(Decorator ):Dynamically add some additional behavior responsibilities to an object without changing the class source code and adding new functions to the object (OCP principle)

Application Example: All subclasses of Java. Io. inputstream and Java. Io. outputstream in JDK

Bridging Mode(BRIDGE): In a software system, some types have two or more dimensional changes due to their own logic. The bridge mode can be used to cope with such multi-dimensional changes.

Intention of the Bridge Mode: separates the abstract part from the implementation part so that they can all change independently.

Appearance Mode(Facade ):A unified interface is provided to access a group of interfaces in the subsystem. The interface defines a high-level interface to make the subsystem easier to use.

Proxy Mode(Proxy ):Proxy mode provides a proxy for an object to control its access.

Application Example: Java. Lang. Reflect. Proxy and Java. RMI

Meta Mode(Flyweight ):The sharing technology is used to effectively support a large number of fine-grained objects.

Application Example: Java. Lang. INTEGER (Boolean, character, byte, short, long)

 

Behavior mode

Rule Mode(Strategy ):Defines algorithm families and encapsulates them separately so that they can be replaced with each other. This pattern makes the algorithm changes independent of the customers who use the algorithm.

Application Example: Compare () of Java. util. Comparator ()

Template Mode(Template ):Defines algorithm steps and delays implementation of these steps to sub-classes. The template method mode provides an important technique for code reuse.

Application Example: Java. Lang. classloader. loadclass ();

Observer Mode(Observer ):Define one-to-multiple dependencies between objects. When an object changes its state, all objects dependent on it will receive notifications and perform corresponding operations.

Application Example: javax. servlet. http. httpsessionbindinglistener

Status Mode(State ):The running object changes its behavior when its internal status changes. The object seems to have modified its class.

Iteration Mode(Iterator ):Provides a method to access each element in a set object sequentially without exposing its internal representation.

Application Example: Java. util. iterator

Command mode(Command ):Encapsulate a request as an object. This allows you to parameterize other objects using different requests, queues, or log requests. The command mode also supports revocation.

Application Example: implements a subclass of the Java. Lang. runnable interface.

Responsibility Chain Model(Chain of responsibility ):When multiple objects are required to process requests, you can consider using the responsibility chain mode.

Application Example: javax. servlet. Filter. dofilter ()

Interpreter Mode(Interpreter ):Interpreter is a special design pattern that creates an interpreter that is used to interpret pre-defined syntaxes for specific computer programming languages. in short, the interpreter mode is a simple syntax interpreter.

Application Example: subclass of Java. util. RegEx. Pattern java. Text. Format

Intermediary Mode(Mediator ):Centralized and complex communication and control methods between related objects.

Application Example: scheldulexxx () in Java. util. Timer ()

Memorandum Mode(Memento ):When you need to let the object return the previous state, it is in the memorandum mode.

Application Example: Java. util. Date java. Io. serializable. in Java, you can use the serialization mechanism to save the object state.

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.