设计模式之策略模式
关注我,升职加薪就是你!
本次讲解不搞参杂别的,直接上demo。
-
定义一个接口ITestService。
/** * @author: Max * @time: 2022/6/10 * @description: 策略模式接口 */ public interface ITestService { void write(); }
-
定义接口ITestService的实现类TestAServiceImpl。
import com.example.demo.testorg.service.ITestService; /** * @author: Max * @time: 2022/6/10 * @description: 策略模式接口的实现类 */ @Service public class TestAServiceImpl implements ITestService { @Override public void write() { System.out.println("TestA..."); } }
-
定义接口ITestService的实现类TestBServiceImpl。
import com.example.demo.testorg.service.ITestService; import org.springframework.stereotype.Service; /** * @author: Max * @time: 2022/6/10 * @description: 策略模式接口的实现类 */ @Service public class TestBServiceImpl implements ITestService { @Override public void write() { System.out.println("TestB..."); } }
-
定义接口ITestService的实现类TestCServiceImpl。
import com.example.demo.testorg.service.ITestService; import org.springframework.stereotype.Service; /** * @author: Max * @time: 2022/6/10 * @description: 策略模式接口的实现类 */ @Service public class TestCServiceImpl implements ITestService { @Override public void write() { System.out.println("TestC"); } }
-
接下来我们写一个方法,获取我们想要的实现类,并且使用具体的方法实现。这里使用了map,避免使用难看的
if / else
。import com.example.demo.testorg.service.ITestService; import com.example.demo.testorg.service.impl.TestAServiceImpl; import com.example.demo.testorg.service.impl.TestBServiceImpl; import com.example.demo.testorg.service.impl.TestCServiceImpl; import java.util.HashMap; import java.util.Map; /** * @author: Max * @time: 2022/6/10 * @description: 策略模式之具体策略 */ public class TestHandler { public static void main(String[] args) { ITestService testService = getTestService("testA"); testService.write(); } /** * @Author:徐章强 * @Description: * @Date:2022/6/10 * @Param:[param] * @Return:com.example.demo.testorg.service.ITestService */ public static ITestService getTestService(String param) { Map<String, ITestService> mapTestService = new HashMap<>(); mapTestService.put("testA", new TestAServiceImpl()); mapTestService.put("testB", new TestBServiceImpl()); mapTestService.put("testC", new TestCServiceImpl()); ITestService iTestService = mapTestService.get(param); return iTestService; } }
完事。
关注我,升职加薪就是你!