JAVA Transformation (nine) Design Patterns Decorator design pattern

Foreword

      This chapter describes the design mode decorator design pattern knowledge

method

1. Concept

And bridging mode is similar to the pattern but also to solve the problem of class explosion. But Decorator focus on the extension of the real role is relatively stable. Real role in bridging mode between the continuous multi-dimensional change is uncertain.

2. The realization of ideas decorator pattern

1) Create the appropriate project

Wherein, Car (car) as the basic object, Feature Car class interface with the basic functions, SuperCar class decoration.

ACar, AACar, AAACar for the car three distinct characteristics.

2) Code Display

Car:

package decorator;

/**
 * 真实对象-普通汽车类
 * 更高级的车为ACar、AACar、AAACar以此类推
 * @author jwang
 *
 */
public class Car implements Feature{

	@Override
	public void move() {
		System.out.println("普通车行走");
	}
	
}

Feature:

package decorator;

public interface Feature {
	/**
	 * 车辆行驶方法
	 */
	public void move();
}

SuperCar:

package decorator;
/**
 * 装饰器类,用来扩充基本对象的功能
 * @author jwang
 *
 */
public class SuperCar implements Feature{

	private Feature car;
	
	public SuperCar(Feature car) {
		super();
		this.car = car;
	}

	@Override
	public void move() {
		car.move();
	}

}

One characteristic of the car ACar:

package decorator;

public class ACar extends SuperCar {

	public ACar(Feature car) {
		super(car);
	}
	//A类车新特性
	public void A(){
		System.out.println("A类汽车还可以飞");
	}
	@Override
	public void move() {
		super.move();
		A();
	}
}

This shows the type, A Class car can pass over any expansion of their functions.

3) writing test code to test

Test:

package decorator;

public class Test {

	public static void main(String[] args) {
		//普通车的行走方式
		Car car = new Car();
		car.move();
		System.out.println("-----------------------");
		//普通车加入A类车行走的优势
		ACar aCar = new ACar(car);
		aCar.move();
		System.out.println("-----------------------");
		//普通车加入AA类车行走的优势
		AACar aaCar = new AACar(car);
		aaCar.move();
		System.out.println("-----------------------");
		//普通车加入AA类车行走的优势和AAA类车行走的优势
		AACar aaCar2 = new AACar(new AAACar(car));
		aaCar2.move();
	}
}

Program execution results:


Guess you like

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