strategy设计模式

strategy设计模式

有多种不同算法来实现同一个任务,使client根据需要动态切换算法,而不是写死在代码里

类结构

  • 一个具体类(Context,环境类,上下文类)
  • 一个抽象策略接口
  • 多个具体策略类

具体类中,存在需要动态切换算法的方法
采用Dependency的方式通过方法传参建立临时的delegation关系

具体类

// Context.java
public class Context {
	public void doSomething(Strategy strategy) {
		strategy.algorithm();
	}
}

抽象策略接口

// Strategy.java
public interface Strategy {
	void algorithm();
}

具体策略类1

// ConcreteStrategy1.java
public class ConcreteStrategy1 implements Strategy {
	@override
	public void algorithm() {
		System.out.pirntln("do something with strategy1");
	}
}

具体策略类2

// ConcreteStrategy2.java
public class ConcreteStrategy2 implements Strategy {
	@override
	public void algorithm() {
		System.out.println("do something with strategy2");
	}
}

客户端

// Client.java
public static void main(String[] args) {
	Context context = new Context();
	Strategy strategy1 = new ConcreteStrategy1();
	Strategy strategy2 = new ConcreteStrategy2();
	context.doSomething(strategy1);
	context.doSomething(strategy2);
}
// in terminal
// do something with strategy1
// do something with strategy2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值