(CZ Java Basics) Design pattern notes

Source: Internet
Author: User

I. Object-oriented thought design principles 1. Principle of single responsibility

In fact, developers often say "high cohesion, low coupling", that is, each class should have only one responsibility, external can only provide a function, and the cause of class changes should be only one. In design mode, all design patterns follow this principle.

2. Opening and closing principle

The core idea is that an object is open to the extension and closed to the modification.
The open and closed principle means that changes to the class are made by adding code rather than modifying the existing code.
In other words, once the software developer writes out the code that can be run, it should not change it, but to ensure that it can continue to run, how can it do this? This requires abstraction and polymorphism, which abstracts the content of the possible changes, thus making the abstract part relatively stable. And the concrete implementation can be changed and expanded.

3. The Richter Replacement principle

The core idea: wherever the parent class appears, it can be substituted with its subclasses.
In fact, it is said that the objects in the same inheritance system should have common behavioral characteristics.

4. Dependency Injection principle

The core idea: to rely on abstraction, do not rely on concrete implementation.

In fact, in an application, all classes, if used or dependent on other classes, should rely on the abstract classes of these other classes instead of the concrete classes of those other classes. To implement this principle, we are required to program for abstract classes or interfaces when programming, rather than for specific implementations.

5. Interface Separation principle

Core idea: The program should not be forced to rely on methods that they do not need to use.

In fact, it is said: an interface does not need to provide too much behavior, an interface should only provide an external function, should not be all operations are encapsulated in an interface.

6. Dimitri Principle

Core idea: One object should know as little as possible about other objects

In fact, it is said: reduce the coupling between the various objects, improve the maintainability of the system. The module should be programmed only through the interface, regardless of the internal workings of the module, it can reduce the coupling degree of each module to a minimum, promote the reuse of software

Two. Design mode 1. Overview

1.1. Concept

Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability.

Design patterns are not a method or a technique, but a thought

The design pattern is independent of the specific language, the learning design pattern is to establish the object-oriented thought, as far as possible interface programming, low-coupling, cohesion poly, so that the design program can be reused

Learning Design patterns can promote an understanding of object-oriented thinking and vice versa. They complement each other

1.2. Elements

The name must have a simple, meaningful name

Problem description when to use pattern

Solution describes the components of the design and how to solve the problem

Effect description mode effect and pros and cons

1.3. Classification

Create model object creation: Simple Factory mode, factory method mode, abstract Factory mode, builder mode, prototype mode, Singleton mode. (6)

Structure Pattern Object Composition (structure): Appearance mode, adapter mode, proxy mode, decoration mode, bridge mode, combination mode, and enjoy meta mode. (7)

Behavioral Pattern Object Behavior: Template method mode, observer mode, State mode, responsibility chain mode, Command mode, visitor mode, policy mode, Memo mode, iterator mode, interpreter mode. (10)

2. Creation mode specific use 2.1. Simple Factory mode

also called the Static Factory method pattern, which defines a specific factory class that is responsible for creating instances of some classes

Advantages
Clients do not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class
Disadvantages
This static factory class is responsible for the creation of all objects, if new objects are added, or some objects are created in different ways, it is necessary to constantly modify the factory class, not conducive to later maintenance

 Public classDemo { Public Static voidMain (string[] args) {}}classAnimalfactory {Privateanimalfactory () {}StaticAnimal creatanimal (String type) {if("Dog". Equals (Type) {            return NewDog (); }        if("Cat". Equals (Type )return NewCat (); return NULL; }}Abstract classAnimal {Abstract voideat ();}classDogextendsAnimal {@Overridevoideat () {System.out.println ("Dog Eats meat"); }}classCatextendsAnimal {@Overridevoideat () {System.out.println ("Cat Eats fish"); }}
2.2. Factory Method Mode

In factory method mode, the abstract factory class is responsible for defining the interfaces that create objects, and the creation of specific objects is implemented by the concrete classes that inherit the abstract factory.
Advantages
The client does not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class, if there are new objects added, only need to add a specific class and the specific factory class, do not affect the existing code, late maintenance easy, enhance the system extensibility
Disadvantages
Additional writing code required, increased workload

 Public classDemo { Public Static voidMain (string[] args) {Factory df=Newdogfactory (); Animal a=Df.creatanimal ();        A.eat (); Factory CF=Newcatfactory (); Animal b=Cf.creatanimal ();    B.eat (); }}Interfacefactory{Animal creatanimal ();}classDogfactoryImplementsfactory{@Override PublicAnimal Creatanimal () {return NewDog (); }    }classCatfactoryImplementsfactory{@Override PublicAnimal Creatanimal () {return NewCat (); }    }Abstract classAnimal {Abstract voideat ();}classDogextendsAnimal {@Overridevoideat () {System.out.println ("Dog Eats meat"); }}classCatextendsAnimal {@Overridevoideat () {System.out.println ("Cat Eats fish"); }}
2.3. Overview of the single case design pattern

The singleton pattern is to make sure that the class has only one object in memory and that the instance must be created automatically and provided externally. Advantages
There is only one object in system memory, so system resources can be saved, and for some object singleton patterns that need to be created and destroyed frequently, the performance of the system can be improved.
Disadvantages
There is no abstraction layer, so the extension is difficult.
Too heavy a duty to violate a single duty in a certain procedure

    • Hunger type

A good object is created when the class is loaded

 Public classDemo { Public Static voidMain (string[] args) {Student S1=student.getstudent (); Student S2=student.getstudent (); System.out.println (S1==S2); }}classStudent {PrivateStudent () {//let the outside world not create objects of this class    }    Private StaticStudent s =NewStudent ();//To not allow direct access to modify this value, add private    StaticStudent getstudent () {returns; }}
    • Lazy Style

To create an object when you use it.

May cause thread safety issues

 Public classDemo { Public Static voidMain (string[] args) {Teacher T1=Teacher.getteacher (); Teacher T2=Teacher.getteacher (); SYSTEM.OUT.PRINTLN (T1==T2); }}classTeacher {PrivateTeacher () {}Private StaticTeacher T =NULL; StaticTeacher Getteacher () {if(T = =NULL) T=NewTeacher (); returnT; }}
Application of single-case mode---runtime class
 Public class Demo {    publicstaticvoid  main (string[] args) {        Runtime run= runtime.getruntime ();         Try {            run.exec ("Calc");         Catch (IOException e) {            //  TODO auto-generated catch block             E.printstacktrace ();     }}}

2017.5.3

(CZ Java Basics) Design pattern notes

Related Article

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.