On the six principles of design pattern __ The principle of open closure

Source: Internet
Author: User
Tags closure

forwarding Please indicate the source: http://blog.csdn.net/qq_28055429/article/details/51507170


One, single responsibility principle: in the case of a class, there should be only one reason for its change (that is, the implementation class should be responsible for a single)

English--single Responsibility Principle

Abbreviation: SRP

As an example:

Parent class: Animal

public class Animal {
	
	 void Move (String Animal) {
		System.out.println (Animal + "is primarily moved by foot");
	}
Test class:
  <pre name= "code" class= "Java" >public class Srptest {public

	static void Main (string[] args) {
		Animal Animal = new Animal ();
		Animal.move ("dog");
		Animal.move ("cat");
		Animal.move ("mouse");

	}

Output:

A dog is a cat that moves mainly by its feet, and the
Mouse is mainly moved with its feet.
So the problem is, when you add a bird, it prints out that the bird is mainly moved with its feet (but it seems to be wings, and this is supposed to be wings)

At this point, you need to change the code:

If you change this:

public class Animal {
	
	 void Move (String Animal) {
		if ("Bird". Equals (Animal)) {
			System.out.println (Animal +) is mainly moved by Wings ");
		else{
			System.out.println (animal + "is mainly moved with the Foot");}
		}
Yes, can actually output, but contrary to the principle of a single duty, if you want to be divided into similar to the owl and other major wings in the night moving birds, and by the wings of the birds moving in the daytime, and how, and, again.

This is the time to consider a single principle of responsibility:

The first one: it seems a bit of a violation, but in the way it seems not to violate:

public class Animal {
	
	 void Move (String Animal) {
			System.out.println (Animal + "is primarily moved by Wings");
		}
    void Moven (String animal) {
			System.out.println (animal + "is primarily moved with Wings");
		}
    


The second type:

use two classes, that is, a class to manage one principle:

public class Animal {
	
	 void Move (String Animal) {
			System.out.println (Animal + "is primarily moved by Wings");
		}


public class Birds {
	void Move (String animal) {
		System.out.println (animal + "is primarily moved by Wings");
	}

Test class:

public class Srptest {public

	static void Main (string[] args) {
		Animal Animal = new Animal ();
		Animal.move ("dog");
		Animal.move ("cat");
		Animal.move ("mouse");
		Birds birds = new birds ();
		Birds.move ("Bird");

	}




Two, open closure principle: to expand---development, to change----closed

English: Opencloseprinciple

Abbreviation: OCP

is to say: do not change the source code (existing code), but should add a new class (such as subclasses, etc.)

such as version update, etc.


Version update: Try not to change the source code, you can add new features

Employee tardiness problem: You can make late night work, how late you have to work overtime and so on system

That is: The total length of work closed, for a little late open



three, the Richter substitution principle: descendant Parent, program behavior does not change (somewhat like inheritance)

English: Liskov substitution principle

Abbreviation: LSP

Understanding: Subclasses must be able to replace their parent type so that the parent module can use extensibility without changing

such as animals,

Son: Dog, cat, ox

Also as an example of a arithmetic:

To add:

Package testtwo;

public class Console {
	int addnumber (int a, int b) {return
		(A + b);
	}
}

Test class:

Package testtwo;

public class Test {public

	static void Main (string[] args) {
		Console console = new console ();
		int result = Console.addnumber (8, 2);
		SYSTEM.OUT.PRINTLN ("Results are:" + result);
	}


Output results:

The result: 10

If you want to add and multiply it first, such as (8 + 2) * 4

so you might say that I just change the console directly, but in case you have a lot of classes that use the console example, then error prone,

So you can create a new class to inherit, console unchanged,

such as code:

Package testtwo;

public class Aconsonle extends console{
	int addnumber (int a, int b) {return
		(A + b);
	}
	int mulnumber (int a, int b) {return
		(A * b);
	}
}

Test class:

Package testtwo;

public class Test {public

	static void Main (string[] args) {

		Aconsonle aconsole = new Aconsonle ();
		int c = Aconsole.addnumber (8, 2);
		int result = Aconsole.mulnumber (c, 4);
		SYSTEM.OUT.PRINTLN ("Output is:" + result);
		
	}


Output:

The output result is: 40


Four: Reliance reversal (SET) principle:

English: Dependence inversion principle,

Short DIP

Understand:

(1) abstraction should not depend on detail, the details should depend on abstraction

(for interface programming, do not program for reality)

(2) High-level modules should not rely on the underlying modules, two should be dependent on abstraction

Abstract: Refers to an interface or abstract class




Example 1: If the high-level to access the database, at this time, habitual we like to write a class to achieve access to the database operations (low-level),

High-level-------the bottom of the--------database

But at this time, suddenly customer requirements can be based on their own preferences to choose different storage mode, and how to do it.


Example 2: Through code examples,

Package threetest;

public class Dog  {public
	void Eat () {
		System.out.println) ("Dog is eating.") ");
	}

}

Animal class:

public class Animal {public
	void Animal (Dog Dog) {
		dog.eat ();
	}
}
Test class:

<pre name= "code" class= "Java" >package threetest;

public class Test {public
	static void Main (string[] args) {
		Animal a = new Animal ();
		Dog Dog = new Dog ();
		A.animal (dog);
		A.animal (dog);
		A.animal (dog);
	
	}

Output results:

The dog is eating. The dog is eating. The dog is eating.

So this time, suddenly want to test class, and then increase the cat is eating, how to change it. (Add Mice 、、、。 )

Then it's time to think of dependency abstractions, and here's an example of an interface:

Code:

Interface class Ieat:

Package threetest;

Public interface Ieat {public
	void eat ();
}


Dog Category:

Package threetest;

public class Dog  implements ieat{public
	void Eat () {
		System.out.println ("Dog is eating.") ");
	}

}

Cat Category:

Package threetest;

public class Cat implements ieat{public
	void Eat () {
		System.out.println ("Cat is eating.") ");
	}
}

High class:

Package threetest;

public class Animal {public
	void Animal (Ieat Ieat) {
		ieat.eat ();
	}
}

Test class:

Package threetest;

public class Test {public
	static void Main (string[] args) {
		Animal a = new Animal ();
		Dog Dog = new Dog ();
		Cat cat = new Cat ();
		A.animal (dog);
		A.animal (dog);
		A.animal (dog);
		A.animal (cat);
		A.animal (cat);
		A.animal (cat);
	}


Output results:

The dog is eating. The
dog is eating. The
dog is eating. The
cat is eating. The
cat is eating. The
cat is eating.

This shows: high-class animal rely on abstraction (here is the interface)

Bottom class: Cat, Dog also relies on abstraction (here is the interface)

Five, Dimitri Law: reducing the coupling between classes

English (Law of Demeter,lod) is also known as the minimum knowledge principle (least knowledge PRINCIPLE,LKP)

The fundamental idea: to emphasize the loose coupling between classes,

..... The less the class knows about the classes they depend on, the better.

...... Communicate with a direct friend

Direct friends include:

1 The current object itself (this)
2 in parametric form to the object in the current object method
3 objects directly referenced by instance variables of the current object
4 instance variables of the current object if it is a cluster, then the elements of the aggregation are also friends
5 objects created by the current object
Any object, if one of the above conditions is met, is the "friend" of the current object, or "stranger".

can also say:

The class that appears in the input and output parameters of a member variable, method is called a member friend class, and the class that appears inside the method body does not belong to a friend class.


Example:

Animal class: Dog class belongs to the direct friend class, because it is through the input and output parameters of the method to become friends, when foot in the method body count, does not belong to the direct friend

The method belongs to the behavior of the class, and a class does not know that his behavior is dependent on other classes, which violates the Dimitri law.

Package fourtest;

Import java.util.ArrayList;
Import java.util.List;

public class Animal {public
	void count (Dog Dog) {
		list<foot> List = new arraylist<foot> ();
		for (int i = 0; i < i++) {
			list.add (new Foot ());
		}
		Dog.countfoot (list);
		
	}

</pre><pre name= "code" class= "Java" >dog class:
</pre><pre name= "code" class= "java" ><pre name= "code" class= "Java" >package fourtest;
Import java.util.List;
public class Dog {
	void Countfoot (List list) {
		System.out.println ("Common foot:" + list.size () + "only");
	}

Foot class: No code is written here

Package fourtest;
public class Foot {

}

Test class:

Package fourtest;
public class Test {public
	static void Main (string[] args) {
		Animal al = new Animal ();
		Dog Dog = new Dog ();
		Al.count (dog);
	}


Output:

Foot Total: 10
Yes, the result is true, but it violates the Dimitri law.

should read:

Animal class:

Package fourtest;
Import java.util.ArrayList;
Import java.util.List;
public class Animal {public
	void count (Dog Dog) {
		dog.countfoot ();
		
	}
}


Dog class:

Package fourtest;
Import java.util.ArrayList;
Import java.util.List;
public class Dog {public
	list<foot> List;
	Public Dog (list<foot> footlist) {
		this.list = footlist;
	}
	void Countfoot () {
		System.out.println ("Common feet:" + list.size () + "only");
	}	

Foot class unchanged, or no code:

Test class:

Package fourtest;
Import java.util.ArrayList;
Import java.util.List;

public class Test {public
	static void Main (string[] args) {
		list<foot> List = new Arraylist<foot> () ;	Create a list table with type Foot for
		(int i = 0; i < i++) {				//Store data
			List.add (New Foot ());
		}
		Dog Dog = new Dog (list);				Create dog object, list as parameter
		Animal al = new Animal ();			Create Animal Object
		al.count (dog);						Call the Count method for the animal object, dog as the Object
		
	}
}
Output:

Foot Total: 10

Also like the picture:



Each control is found to be related to other controls, so that if you modify one control, other controls may be driven,

If the Dimitri law can be changed to: Add an intermediary (intermediate Class) to manage, as follows:




Six, the principle of interface isolation:

English: Interface Segregation principle

Abbreviation: ISP

The client should not rely on interfaces that it does not need, and a class's dependency on a class should be based on the smallest interface

Attention:
(1) The interface is as small as possible, but there is a limit.

(2) Customizing a service for a dependent interface, exposing only the methods it needs for the calling class, and hiding the unwanted methods.
(3) Improve cohesion and reduce external interaction. Make the interface do the most things in the least possible way.


As an example:

Animal interface:

Package fivetest;
Interface Animal {public
	void eat ();
	public void Move ();
	public void Sleep ();
	public void relax ();
}
Class Dog:

Package fivetest;
public class Dog implements animal{
	//Not abstract, need to rewrite
	//We rewrite the previous three methods public
	void Eat () {
		System.out.println ("The Dog is Eating");
	}
	public void Move () {
		System.out.println ("Dog is moving");
	}
	public void Sleep () {
		System.out.println ("Dog is Sleeping");	
	}
	public void Relax () {}
}

Cat class:

Package fivetest;
public class Cat implements animal{public
	void Eat () {}
	//Here rewrite the following three methods public
	void Move () {
		System.out . println ("Cat is Moving");
	public void Sleep () {
		System.out.println ("Cat is Sleeping");		
	}
	public void Relax () {
		System.out.println ("Cat is resting");	
	}

Danimal class:


Package fivetest;

public class Danimal {public
	void A1 (Animal Animal) {
	    animal.eat ();
	}
	public void A2 (Animal Animal) {
		animal.move ();
	}
	public void A3 (Animal Animal) {
		animal.sleep ();
	}
}

Canimal class:

Package fivetest;

 Class Canimal {public
	void B2 (Animal Animal) {
		animal.move ();
	}
	public void B3 (Animal Animal) {
		animal.sleep ();
	}
	public void B4 (Animal Animal) {
	    animal.relax ();
	}
}
Testing class: Test

Package fivetest;

public class Test {public
	static void Main (string[] args) {

		canimal c = new Canimal ();
		Cat Cat   = new Cat ();
		C.B2 (cat);
		C.B3 (cat);
		C.B4 (cat);
		
		Danimal d = new Danimal ();
		Dog   Dog = new Dog ();
		D.A1 (dog);
		D.A2 (dog);
		D.a3 (dog);
	}	
Output results:

Cat is moving cat is
sleeping
cat is resting
dog is eating dog is
moving
dog is sleeping
Use the Dimitri rule to change the following code:


Interface: 4:

Public interface Eat {public
	void Eat ();
}

Public interface Move {public
	void Move ();
}

Public interface Sleep {public
	void sleep ();
}

Public interface Relax {public
	void Relax ();
}


Dog class:

public class Dog implements Eat, move, sleep{
	//We rewrite the previous three methods public
	void Eat () {
		System.out.println ("Dog is eating" ");
	}
	public void Move () {
		System.out.println ("Dog is moving");
	}
	public void Sleep () {
		System.out.println ("Dog is Sleeping");	
	}

Cat class:

Public class Cat implements moves, sleep, relax{
	//Here rewrite the following three methods public
	void Move () {
		System.out.println ("Cat is moving") );	
	}
	public void Sleep () {
		System.out.println ("Cat is Sleeping");		
	}
	public void Relax () {
		System.out.println ("Cat is resting");	
	}
Danimal class:

public class Danimal {public
	void A1 (Eat e) {
	    e.eat ();
	}
	public void A2 (move m) {
		m.move ();
	}
	public void A3 (sleep s) {
		s.sleep ();
	}
}

Canimal class:

Class Canimal {public
	void B2 (move m) {
		m.move ();
	}
	public void B3 (sleep s) {
		s.sleep ();
	}
	public void B4 (Relax r) {
	    r.relax ();
	}
}

Test class:
public class Test {public
	static void Main (string[] args) {

		canimal c = new Canimal ();
		Cat Cat   = new Cat ();
		C.B2 (cat);
		C.B3 (cat);
		C.B4 (cat);
		
		Danimal d = new Danimal ();
		Dog   Dog = new Dog ();
		D.A1 (dog);
		D.A2 (dog);
		D.a3 (dog);
	}	

Output results:
Cat is moving cat is
sleeping
cat is resting
dog is eating dog is
moving
dog is sleeping











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.