/**
策略设计模式:
把可变的行为抽象出来,想成一个算法簇,这样可以让我们的应用更利于变化。
在使用抽象类和接口时,我们优先选择接口
OO思想:面向接口编程,低耦合,高内聚
*/
interface GoHomeable
{
public void goHome(String job);
}
class GoHomeableImplByFly implements GoHomeable
{
public void goHome(String job){
System.out.println(job + "穷的就剩钱了,要坐飞机回家。。。");
}
}
class GoHomeableImplByFoot implements GoHomeable
{
public void goHome(String job){
System.out.println(job + "把钱花光了,只能步行回家。。。");
}
}
class GoHomeableImplByTrain implements GoHomeable
{
public void goHome(String job){
System.out.println(job + "是穷屌丝,站火车回家。。。");
}
}
class Person
{
private String job;
private GoHomeable gh;
public Person(String job){
this.job = job;
}
public void setGH(GoHomeable gh){
this.gh = gh;
}
public void setJob(String job){
this.job = job;
}
public String getJob(){
return job;
}
public void goHome(){
gh.goHome(job);
}
}
class Student extends Person
{
public Student(String job){
super(job);
}
}
class Worker extends Person
{
public Worker(String job){
super(job);
}
}
class Boos extends Person
{
public Boos(String job){
super(job);
}
}
class CeLueMoShi
{
public static void main(String[] args)
{
Student student = new Student("学生");
student.setGH(new GoHomeableImplByTrain());
student.goHome();
Worker worker = new Worker("工人");
worker.setGH(new GoHomeableImplByFoot());
worker.goHome();
Boos boos = new Boos("大老板");
boos.setGH(new GoHomeableImplByFly());
boos.goHome();
}
}
策略设计模式:把可变的行为抽象出来形成一个算法簇
最新推荐文章于 2024-07-28 14:31:10 发布