JAVA Transformation (X) design pattern design model

Foreword

      This chapter explains the basics of design patterns Design patterns

method

1. Concept

Demeter (Law of Demeter): also called the principle of least knowledge (Least Knowledge Principle abbreviation LKP), that is a subject should have as little understanding of other objects, do not talk to strangers. English abbreviated as: LoD.

In our actual programming, it was always going to invoke a method of the object, so if you call a method related to multiple objects, then we must consider this code to be packaged for use by other programs call, such as a some tools: XXUtil.java

2. The design pattern is not used scenes

1) create the appropriate project

Which we imitate the following scene, just today, just finished the landlord passport, passport process: printing application materials -> pictures -> apply -> payment

Then this four-step design we can operate four categories:

2) preparation of corresponding code

Wherein details include personnel handling class, similar to the other three related classes:

package facade;

public class 办理人员 {
	public void print(){
		System.out.println("--受理相关护照申请--");
	}
}

So we need to apply for a passport to write the following code:

package facade;

import org.junit.Test;

public class TestFacade {

	@Test
	public void testNoFacade(){
		自助打印机 a = new 自助打印机();
		a.print();
		照相师 b = new 照相师();
		b.print();
		办理人员 c = new 办理人员();
		c.print();
		收费员 d = new 收费员();
		d.print();
	}
}

Execution results are as follows:

So if other people need to apply for a passport of the time, you need to perform these four methods is clearly contrary to our Demeter!

This time we need uses appearance mode, these specific steps performed to package a class method, the calling user and the maintenance method of the late.

3 . Design patterns using

1) writing tools PassportUtil

package facade;

/**
 * 申请护照工具类
 * @author jwang
 *
 */
public class PassportUtil {

	public static void apply(){
		自助打印机 a = new 自助打印机();
		a.print();
		照相师 b = new 照相师();
		b.print();
		办理人员 c = new 办理人员();
		c.print();
		收费员 d = new 收费员();
		d.print();
	}
}

2) With the appearance model passport

package facade;

import org.junit.Test;

public class TestFacade {

	/**
	 * 未采用外观模式
	 */
	@Test
	public void testNoFacade(){
		/*自助打印机 a = new 自助打印机();
		a.print();
		照相师 b = new 照相师();
		b.print();
		办理人员 c = new 办理人员();
		c.print();
		收费员 d = new 收费员();
		d.print();*/
	}
	
	/**
	 * 采用外观模式
	 */
	@Test
	public void testFacade(){
		PassportUtil.apply();
	}
}

Execution results are as follows:

In fact, plainly, he is the model the appearance of packaging, packaging, packaging, important things to say three times! !

Guess you like

Origin blog.csdn.net/qq_21046965/article/details/92198996