策略模式

public class T {
    public static void main(String[] args) {
        TravleContext context = new TravleContext(new Car());
        context.selectTravle();
    }
}

/*
环境类Conext
* */
class TravleContext {
    private ITravleStategy iTravleStategy;

    public TravleContext(ITravleStategy iTravleStategy/*算法可以相互替换*/) {
        this.iTravleStategy = iTravleStategy;
    }

    public void selectTravle() {
        iTravleStategy.travle();
    }
}

/*
出行接口 定义算法的骨架
* */
interface ITravleStategy {
    void travle();
}

/*
算法的具体实现
* */
class Bicycle implements ITravleStategy {
    @Override
    public void travle() {
        System.out.println("自行车");
    }
}

/*
算法的具体实现
* */
class Car implements ITravleStategy {

    @Override
    public void travle() {
        System.out.println("小汽车");
    }
}
posted @ 2024-08-16 16:16  干饭达人GoodLucy  阅读(2)  评论(0编辑  收藏  举报