JAVA Design Pattern 4, design pattern 4
I believe that you have understood the JAVA design pattern after several introductions. In this article, we will learn the adapter pattern, proxy pattern, and factory pattern together.
The adapter mode is used in many scenarios. For example, in real life, most of the charging wires in our laptop are three-way plugs. When we encounter a two-way plug-in, how can we charge our notebook? In this case, we need an adapter to convert the two-way plug-in to a three-way plug-in. Next we need to discuss the adapter mode, which is just like the two-to-three-way plug-in here. Next we will use the code to implement the adapter mode with this practical problem.
1. Create a three-way current interface:
/** Define a three-phase charger interface */public interface ThreePathIm {// use three-phase current to supply public void powerWithThree ();}
2. Create a three-way current class:
Public class ThreePath implements ThreePathIm {public void powerWithThree () {System. out. println ("using three-way current supply \ n ");}}
3. Create a two-direction current class:
/** Phase current type */public class TwoPath {public void prowerWithTwo () {System. out. println ("using phase current power supply ");}}
4. Create a binary interface to a three-way Interface Class (interface adapter ):
/** Power interface adapter * two-way interface adapted to three interfaces */public class TwoPlugAdapt implements ThreePathIm {private TwoPath two; public TwoPlugAdapt (TwoPath two) {this. two = two;} public void powerWithThree () {System. out. println ("converted by adapter"); two. prowerWithTwo ();}}
5. Create a class that inherits the binary current class and implements the three-way current interface (inheriting the adapter ):
/** Inherited adapter */public class extendsAdapt extends TwoPath implements ThreePathIm {public void powerWithThree () {System. out. println ("\ n using the inheritance adapter to convert"); this. prowerWithTwo ();}}
6. Create a test class:
Public class noteBook {private ThreePathIm path; private noteBook (ThreePathIm path) {this. path = path;} private void change () {path. powerWithThree ();} public static void main (String [] args) {ThreePathIm tpi = new ThreePath (); tpi. powerWithThree (); TwoPath two = new TwoPath (); // obtain the second-phase interface object ThreePathIm three = new TwoPlugAdapt (two ); // convert the two-phase current interface into three-way noteBook notebook = new noteBook (three); notebook. change (); three = new extendsAdapt (); notebook = new noteBook (three); notebook. change ();}}
There are also many application scenarios in engineering models. For example, we can choose the hair type based on our needs for a popular image production software named "face cute, how is this implemented? Let's take a look at it.
1. Hair type creation interface:
Public interface Hair {public void getHair (); // get hairstyle method}
2. Achieve two hair types through this method:
A. Left score:
Public class leftHair implements Hair {// left partial public void getHair () {System. out. println ("My Hair is left partial ");}}
B. Right score:
Public class rightHair implements Hair {// right partial public void getHair () {System. out. println ("My Hair is right partial ");}}
3. Create a hair Factory:
Public class hairFactory {Hair hair; // obtain the corresponding Hair type class public Hair getHairKey (String key) {if ("left ". equals (key) {hair = new leftHair ();} else if ("right ". equals (key) {hair = new rightHair () ;}return hair ;}// get the corresponding Hair type class public hair getHairClass (String cls) through the Class address) {try {hair = (Hair) Class. forName (cls ). newInstance ();} catch (InstantiationException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IllegalAccessException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace () ;}return hair ;}}
4. Create a test class:
Public class hairTest {/*** test class * @ param args */public static void main (String [] args) {Hair hair1 = new leftHair (); hair hair2 = new rightHair (); hair1.getHair (); hair2.getHair (); // create a class hairFactory factory = new hairFactory (); Hair hair3 = factory through the factory object. getHairKey ("left"); hair3.getHair (); Hair hair4 = factory. getHairClass ("cn.edu. hpu. hair. rightHair "); hair4.getHair ();}}
The proxy mode provides a proxy for an object to control its control.
The following describes how to record the driving time and log when a car is driving. Let's not talk about it. The above code:
1. encapsulate a method for driving a car:
public interface MoveAble { public void move();}
2. Create a car:
Public class Car implements MoveAble {public void move () {try {// System. out. println ("starting a car"); // long start = System. currentTimeMillis (); System. out. println ("driving cars"); Thread. sleep (new Random (). nextInt (1000); // simulate a car running // long end = System. currentTimeMillis (); // System. out. println ("stop a car:" + (end-start) + "millisecond");} catch (InterruptedException e) {e. printStackTrace ();}}}
3. Implement an automobile subclass:
The inheritance method is used to create different sub-classes to record the travel time and log.
Public class Car2 extends Car {public void move () {System. out. println ("cars start driving"); long start = System. currentTimeMillis (); super. move (); // execute the parent class method long end = System. currentTimeMillis (); System. out. println ("stopped cars:" + (end-start) + "millisecond ");}}
4. Create an interface Proxy:
A. Time proxy object:
Public class CarTimeProxy implements MoveAble {public CarTimeProxy (MoveAble m) {this. m = m;} public MoveAble m; public void move () {System. out. println ("cars start driving"); long start = System. currentTimeMillis (); m. move (); long end = System. currentTimeMillis (); System. out. println ("stopped cars:" + (end-start) + "millisecond ");}}
B. Log proxy object:
Public class CarLogProxy implements MoveAble {public CarLogProxy (MoveAble m) {super (); this. m = m;} public MoveAble m; public void move () {System. out. println ("log start"); m. move (); System. out. println ("log end ");}}
5. Test class:
Public class carTest {/*** @ param test */public static void main (String [] args) {// Car car = new Car (); // car. move (); // static proxy in inherited mode // Car car = new Car2 (); // car. move (); // static proxy in interface mode, overlapping operation Car = new car (); MoveAble m1 = new CarTimeProxy (Car); MoveAble m2 = new CarLogProxy (m1 ); m2.move ();}}
6. Implement proxy through JDK:
Public class TimeHander implements InvocationHandler {public TimeHander (Object object) {super (); this. object = object;} Object object;/** parameter: * proxy: proxy object * method: method of the proxy object * args: method parameter */public Object invoke (Object proxy, method Method, Object [] args) throws Throwable {System. out. println ("cars start driving"); long start = System. currentTimeMillis (); method. invoke (object, null); long end = System. currentTimeMillis (); System. out. println ("stopping a car:" + (end-start) + "millisecond"); return null ;}}
7. JDK proxy test:
// Jdk dynamic proxy public class Test {public static void main (String [] args) {Car car = new Car (); InvocationHandler hander = new TimeHander (car ); class cls = car. getClass (); MoveAble m = (MoveAble) Proxy. newProxyInstance (cls. getClassLoader (), cls. getInterfaces (), hander); m. move ();}
}
As of this article, the design patterns in JAVA have been analyzed for everyone. Of course, these are very basic things. To use them in development, you need to exercise more. If you have any questions, leave a message for discussion.