Java设计模式之策略模式

本文详细介绍了策略模式的概念及其应用。通过定义一系列的算法并将每个算法封装起来,使得算法可以在不改变客户端的情况下自由切换。文章提供了策略模式的具体实现示例,包括策略接口及三种不同的策略实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 概念

策略模式(Strategy):它定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化不会影响到使用算法的客户。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)


1,策略接口

package com.strategy;

public interface StrategyInterface {
	void dosomething();	
}
2,具体的策略

策略1:

package com.strategy;

public class Strategy1Impl implements StrategyInterface{
	@Override
	public void dosomething() {
		System.out.println("use Strategy1 do something");
	}

}

策略2

package com.strategy;

public class Strategy2Impl implements StrategyInterface{
	@Override
	public void dosomething() {
		System.out.println("use Strategy2 do something");
	}

}

策略3:

package com.strategy;

public class Strategy3Impl implements StrategyInterface {
	@Override
	public void dosomething() {
		System.out.println("use Strategy3 do something");
	}

}

环境角色,上下文Contex

package com.strategy;

public class StrategyContex {
	
	private StrategyInterface strategyInterface;

	public StrategyInterface getStrategyInterface() {
		return strategyInterface;
	}

	public void setStrategyInterface(StrategyInterface strategyInterface) {
		this.strategyInterface = strategyInterface;
	}

	public StrategyContex(StrategyInterface strategyInterface) {
		super();
		this.strategyInterface = strategyInterface;
	}
	
	public StrategyContex(){}
	
	public void doSomething(){
		this.strategyInterface.dosomething();
		
	}
	
}

客户端调用:

package com.strategy;

public class MainClient {
	
	public static void main(String[] args) {
		StrategyContex contex = new StrategyContex();
		
		contex.setStrategyInterface(new Strategy1Impl());
		contex.doSomething();
		
		contex.setStrategyInterface(new Strategy2Impl());
		contex.doSomething();
		
		contex.setStrategyInterface(new Strategy3Impl());
		contex.doSomething();
	}

}

运行结果:

use Strategy1 do something
use Strategy2 do something
use Strategy3 do something



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值