• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

2021/11/24策略模式

开发技术 开发技术 3小时前 2次浏览

策略者模式

java代码

package Strategy;

public class AirplaneStrategy implements TravelStrategy {
    @Override
    public void goTravel() {
        System.out.println("乘飞机去旅行,飞机策略");	
    }
}

 

package Strategy;

public class BicycleStrategy implements TravelStrategy {
    @Override
    public void goTravel() {
        System.out.println("骑行,骑行策略");	
    }
}

 

package Strategy;

public class CarStrategy implements TravelStrategy {
    @Override
    public void goTravel() {
        System.out.println("自驾游,自驾策略");	
    }
}

 

package Strategy;

public class FootStrategy implements TravelStrategy {
    @Override
    public void goTravel() {
        System.out.println("徒步旅行,徒步策略。");	
    }
}

 

 

package Strategy;

public class StrategyTest {
    public static void main(String[] args) {
        Traveler traveler = new Traveler();
        
        traveler.setTravelStrategy(new AirplaneStrategy());
        traveler.goTravel();
        System.out.println();
        
        traveler.setTravelStrategy(new CarStrategy());
        traveler.goTravel();
        System.out.println();
        
        traveler.setTravelStrategy(new BicycleStrategy());
        traveler.goTravel();
        System.out.println();
        
        traveler.setTravelStrategy(new FootStrategy());
        traveler.goTravel();
        System.out.println();
    }
}

 

package Strategy;

public class Traveler {
    private TravelStrategy travelStrategy;

    public TravelStrategy getTravelStrategy() {
        return travelStrategy;
    }

    public void setTravelStrategy(TravelStrategy travelStrategy) {
        this.travelStrategy = travelStrategy;
    }
    
    public void goTravel() {
        travelStrategy.goTravel();
    }
}

 

 

package Strategy;

public interface TravelStrategy {
    void goTravel();
}

 


程序员灯塔
转载请注明原文链接:2021/11/24策略模式
喜欢 (0)