策略模式(Strategy)
策略模式用来分离算法的实现,类比与if-else;通过上下文对实现进行管理。
约束接口:
public interface IPay {
void pay(Context ctx);
}
上下文:
public class Context implements IPay {
private IPay pay;
protected String name;
protected int price;
public Context(IPay pay, String name, int price) {
this.pay = pay;
this.name = name;
this.price = price;
}
public void pay() {
pay(this);
}
@Override
public void pay(Context ctx) {
pay.pay(ctx);
}
}
实现
public class RMBPay implements IPay {
@Override
public void pay(Context ctx) {
System.out.println(ctx.name+"人民币");
}
}
使用:
public class MyClass {
public static void main(String[] args){
IPay rmbPay=new RMBPay();
Context context=new Context(rmbPay,"ss",22);
context.pay();
}
}
命令模式(Command)
通过将行为封装达到解耦的目的
public interface Command {
void execute();
}
码农:
public class Work implements Command {
@Override
public void execute() {
System.out.println("努力工作");
}
}
加班
public class Work996 implements Command {
@Override
public void execute() {
System.out.println("996工作..");
}
}
主管:
public class Manage implements Command {
private Command command;
public Manage(Command command) {
this.command = command;
}
@Override
public void execute() {
command.execute();
}
}
人事
public class HR implements Command{
private Command command;
public HR(Command command) {
this.command = command;
}
@Override
public void execute() {
command.execute();
}
}
人事干活:
public class Retire implements Command {
private Command command;
@Override
public void execute() {
System.out.println("辞退天天摸鱼的...");
}
}
老板:
public class Boos {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void talk() {
command.execute();
}
}
老板发布命令:
public class MyClass {
public static void main(String[] args) {
//码农
Command work = new Work();
//主管
Manage manage = new Manage(work);
//老板
Boos boos = new Boos();
//老板找主管
boos.setCommand(manage);
//老板让干活
boos.talk();
//人事
HR hr=new HR(new Work996());
//老板找人事1
boos.setCommand(new HR(new Retire()));
//员工上班摸鱼
boos.talk();
//老板找人事2
boos.setCommand(hr);
//员工最近没有奋斗精神
boos.talk();
}
}