策略模式,在不同事物(抽象类)之间发现共同点,将共同点汇集进一个单独的接口中(interface),将不同点放入到接口的实现中(有几个不同就有几个实现)。在生成不同事物的对象时,将接口的实现实例化,作为参数传给不同的事物。这里说的事物不是Transaction。
doTask() {}
doTask() {Overriding code}doTask() {More overriding code}
Your Code
Algorithm variable
<--------Algorithm object 1
<--------Algorithm object 2<--------Algorithm object 3
public interface GoAlgorithm
{
public void go();
}
public abstract class Vehicle
{
private GoAlgorithm goAlogrithm; // algorithm variable
public Vehicle(){}
public void setGoAlgorithm(GoAlgorithm algorithm)
{
goAlogrithm = algorithm;
}
public void go() {
goAlogrithm.go();
}
}
/**
* algorithm object 1
**/
public class GoByDrivingAlgorithm implements GoAlgorithm
{
public void go()
{
System.out.println("Now Im driving");
}
}
/**
* algorithm object 2
**/
public class GoByFlyingAlgorithm implements GoAlgorithm
{
public void go()
{
System.out.println("Now Im flying");
}
}
/**
* algorithm object 3
**/
public class GoByFlyingFast implements GoAlgorithm
{
public void go()
{
System.out.println("Now Im flying fast");
}
}
public class StreetRacer extends Vehicle
{
public StreetRacer()
{
setGoAlgorithm (new GoByDrivingAlgorithm());
}
}
public class Helicopter extends Vehicle
{
public Helicopter() {
setGoAlgorithm(new GoByFlyingAlgorithm());
}
}
public class Jet extends Vehicle
{
public Jet() {
setGoAlgorithm(new GoByFlyingFast());
}
}
public static void main(String args[])
{
StreetRacer streetRacer = new StreetRacer();
streetRacer.go();
Helicopter helicopter = new Helicopter();
helicopter.go();
Jet jet = new Jet();
jet.go();
}