- 面向对象三大特征是封装、继承、多态,多态是面向对象的灵魂
- 实例方法默认是多态的,在运行时根据this的类型来决定调用哪个方法(和代码在哪个类无关)
- 静态方法没有多态
参数静态绑定(方法参数重载是静态选择的,不发生在参数选择上),接收者动态绑定(多态仅对接收对象的类型生效)
策略模式
分离策略逻辑与业务逻辑,每次增加策略可通过添加类来实现,而不是复杂化原先的业务逻辑
- 下面为使用策略模式进行代码重构的案例,重构指的是在不改变原先代码功能的前提下,将原先的代码变得更精炼、可维护性更强 ```java // 测试类 import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test;
public class PriceCalculatorTest { @Test public void test() { Assertions.assertEquals(95, PriceCalculator.calculatePrice(new Discount95Strategy(), 100, User.dios(“屌丝”))); Assertions.assertEquals(100,PriceCalculator.calculatePrice(new OnlyVipDiscountStrategy(), 100, User.dios(“屌丝”))); Assertions.assertEquals(95, PriceCalculator.calculatePrice(new OnlyVipDiscountStrategy(), 100, User.vip(“土豪”))); Assertions.assertEquals(100, PriceCalculator.calculatePrice(new NoDiscountStrategy(), 100, User.vip(“土豪”))); } }
```java
// 工具类User
public class User {
private String name;
private boolean vip;
private User(String name, boolean vip) {
this.name = name;
this.vip = vip;
}
public static User vip(String name) {
return new User(name, true);
}
public static User dios(String name) {
return new User(name, false);
}
public String getName() {
return name;
}
public boolean isVip() {
return vip;
}
}
public class PriceCalculator {
// 使用策略模式重构这个方法,实现三个策略:
// NoDiscountStrategy 不打折
// Discount95Strategy 全场95折
// OnlyVipDiscountStrategy 只有VIP打95折,其他人保持原价
public static int calculatePrice(String discountStrategy, int price, User user) {
switch (discountStrategy) {
case "NoDiscount":
return price;
case "Discount95":
return (int) (price * 0.95);
case "OnlyVip":
{
if (user.isVip()) {
return (int) (price * 0.95);
} else {
return price;
}
}
default:
throw new IllegalStateException("Should not be here!");
}
}
// ---------------------------重构后 -----------------------------
public static int calculatePrice(DiscountStrategy strategy, int price, User user) {
return strategy.discount(price,user);
}
}
public class DiscountStrategy {
public int discount(int price, User user) {
throw new UnsupportedOperationException();
}
}
public class NoDiscountStrategy extends DiscountStrategy {
@Override
public int discount(int price, User user) {
return price;
}
}
public class Discount95Strategy extends DiscountStrategy {
@Override
public int discount(int price, User user) {
return (int) (price * 0.95);
}
}
public class OnlyVipDiscountStrategy extends DiscountStrategy {
@Override
public int discount(int price, User user) {
if (user.isVip()) {
return (int) (price * 0.95);
} else {
return price;
}
}
}
线程池TheadPoolExecutor
- 线程池是策略模式在JDK中的使用,线程池代码逻辑与策略逻辑完全分离,实现代码解耦