Headfirst design pattern - strategy mode

definition

Strategy mode defines the algorithm family, which are encapsulated separately so that they can be replaced with each other. This mode makes the algorithm change independent of the client using the algorithm. The

书中example

书 uses the Duck class to optimize step by step to the strategy mode. Inheritance was used to make different types of ducks have different behavioral methods, but it was found to cause a problem. If a plastic duck inherits the Duck class, then he will have a flight method and a method called. This way the clinker duck can fly, which is obviously unreasonable.

于于书 First used the interface to solve this problem, he mentioned the behavior method to different interfaces, such as: Flyable, Quackble, and then let each subclass of Duck achieve These interfaces. This raises another problem: if you want to have 48 Duck subclasses, you need to create 48 subclasses, and each additional subclass must implement an interface.

Finally, add the behavior interface as a variable in the Duck class, and create corresponding methods in the Duck class to call the implementation methods of these interfaces. This allows you to instantiate different implementations of behavioral interfaces when creating each subclass, so that behavioral methods have different implementations in different Duck subclasses.

实施

1. First realize the Duck class

public abstract class Duck {
	FlyBehavior flyBehavior;
	QuackBehavior quackBehavior;

	public Duck() {
	
	}
	
	public void setFlyBehavior(FlyBehavior fb) {
		flyBehavior = fb;
	}

	public void setQuackBhavior(QuackBehavior qb) {
		quackBehavior = qb;
	}

	public abstract void display();

	public void performFly() {
		flyBehavior.fly();
	}

	public void performQuack() {
		quackBehavior.quack();
	}

	public void swim() {
		System.out.println("All ducks float, even docoys");
	}
}

There are two behavior interfaces of Flybehavior and quackBehavior.

2. Implement the classes corresponding to these two interfaces. If you can't fly, use a rocket to fly, gliding, etc. (code omitted)

3. When the subclass is constructed, the Flybehavior and quackBehavior interfaces of the subclass are instantiated

public class MallardDuck extends Duck {
	public MallardDuck() {
		quackBehavior = new Quack();
		flyBehavior = new FlyWithWings();
	}

	public void display() {
		System.out.println("I`m a real MallardDuck!!!!!");
	}
}

, which realizes which flight method or method is specified by the runtime.