Java设计模式:策略模式

本文探讨了设计模式在实际开发中的应用,通过策略模式实例讲解如何减少条件判断,提高代码复用。学习如何在需要策略切换的场景下,使用接口和匿名内部类或Java 8 Lambda表达式,提升代码灵活性和可维护性。

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

绪论

其实很早以前就看过一些关于设计模式的文章,知道这个很重要,为此还写了一些demo,但是在实际开发过程中基本没有使用过。原因:不习惯,不记得,其实更多的是不明白什么情况下可以使用。所以导致自己的代码又臭又长,还会重复的造一些轮子,使代码看起来毫无亮点。
这次学习设计模式,更多的是分析理解,思考以往编程中哪些地方可以用到这些模式,从而可以使以后的自己在开发相同模块时可以使用。

理解

  1. 一个类的行为可以在运行时动态的更改。
  2. 在多种行为相似的情况下,可以减少if…else…的复杂度。
  3. 需要实现同一个接口。
  4. 参考java.util.Comparator的compare方法。

代码

方式一:

定义接口

public interface Strategy {
	int operation(int a, int b);
}

实现加

public class StrategyAdd implements Strategy {
	@Override
	public int operation(int a, int b) {
		return a + b;
	}
}

实现减

public class StrategySubtract implements Strategy {
	@Override
	public int operation(int a, int b) {
		return a - b;
	}
}

计算管理

public class Calculate {
	private Strategy strategy;
	
	public Calculate(Strategy strategy) {
		this.strategy = strategy;
	}
	
	public int operation(int a, int b) {
		return strategy.operation(a, b);
	}
}

主方法

public class Main {
	public static void main(String[] args) {
		Calculate calculate = new Calculate(new StrategyAdd());
		System.out.println("1 + 2 = " + calculate.operation(1, 2));
		
		calculate = new Calculate(new StrategySubtract());
		System.out.println("1 - 2 = " + calculate.operation(1, 2));
	}
}
方式二:

保留Strategy与其实现,重写Calculate。 注意:最好在Strategy加上@FunctionalInterface注解。

public class Calculate {
	public int operation(int a, int b, Strategy strategy) {
		return strategy.operation(a, b);
	}
}

主方法

public class Main {
	public static void main(String[] args) {
		Calculate calculate = new Calculate();
		System.out.println("4 + 2 = " + calculate.operation(4, 2, new StrategyAdd()));
		System.out.println("4 - 2 = " + calculate.operation(4, 2, new StrategySubtract()));
		// 可以用匿名内部类重新定义实现
		System.out.println("4 * 2 = " + calculate.operation(4, 2, new Strategy() {
			@Override
			public int operation(int a, int b) {
				return a * b;
			}
		}));
		// java8 Lambda
		System.out.println("4 / 2 = " + calculate.operation(4, 2, (a, b) -> a / b));
	}
}

结果

方式一结果:

在这里插入图片描述

方式二结果:

在这里插入图片描述

(若有什么错误,请留言指正,3Q)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值