简介
本文介绍工厂模式的工厂方法模式。
优缺点
优点
解决了简单工厂的缺点,新增工厂类时很方便,符合开闭原则。
缺点
无。
实战
需求:根据参数(小米、华为)获取一个Phone(手机)对象,并调用它打电话方法。
代码结构
手机产品
接口
package com.knife.designPattern.product; public interface Phone { /** * 打电话 */ String callUp(); }
实现类
小米手机实现类
package com.knife.designPattern.product.impl; import com.knife.designPattern.product.Phone; import lombok.Data; @Data public class XiaoMiPhoneImpl implements Phone { /** * CPU个数 */ private Integer cpuCount; /** * 内存大小 */ private Integer memoryStorage; public XiaoMiImpl(Integer cpuCount, Integer memoryStorage) { this.cpuCount = cpuCount; this.memoryStorage = memoryStorage; } @Override public String callUp() { return "小米手机打电话"; } }
华为手机实现类
package com.knife.designPattern.product.impl; import com.knife.designPattern.product.Phone; import lombok.Data; @Data public class HuaWeiPhoneImpl implements Phone { /** * CPU个数 */ private Integer cpuCount; /** * 内存大小 */ private Integer memoryStorage; public HuaWeiImpl(Integer cpuCount, Integer memoryStorage) { this.cpuCount = cpuCount; this.memoryStorage = memoryStorage; } @Override public String callUp() { return "华为手机打电话"; } }
工厂类
接口
package com.knife.designPattern.factory; import com.knife.designPattern.product.Phone; public interface PhoneFactory { Phone createPhone(); }
实现
小米实现类
package com.knife.designPattern.factory.impl; import com.knife.designPattern.factory.PhoneFactory; import com.knife.designPattern.product.Phone; import com.knife.designPattern.product.impl.XiaoMiPhoneImpl; public class XiaoMiFactoryImpl implements PhoneFactory { public Phone createPhone() { return new XiaoMiPhoneImpl(4, 21); } }
华为实现类
package com.knife.designPattern.factory.impl; import com.knife.designPattern.factory.PhoneFactory; import com.knife.designPattern.product.Phone; import com.knife.designPattern.product.impl.HuaWeiPhoneImpl; public class HuaWeiFactoryImpl implements PhoneFactory { public Phone createPhone() { return new HuaWeiPhoneImpl(4, 21); } }
测试类
package com.knife.designPattern.controller; import com.knife.designPattern.factory.impl.HuaWeiFactoryImpl; import com.knife.designPattern.factory.impl.XiaoMiFactoryImpl; import com.knife.designPattern.product.Phone; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Api(tags = "产品") @RestController @RequestMapping("product") public class ProductController { @ApiOperation("手机") @GetMapping("phone") public String phone(String name) { Phone phone = null; switch (name) { case "华为": phone = new HuaWeiFactoryImpl().createPhone(); break; case "小米": phone = new XiaoMiFactoryImpl().createPhone(); break; default: return null; } if (phone != null) { return phone.callUp(); } return null; } }
这里是判断了产品名字,然后去调用相关的工厂,这里也可以像简单工厂一样,把这个步骤封装起来。
源码下载
此隐藏内容仅限VIP查看升级VIP
测试
访问:http://localhost:8080/doc.html(当然,你用Postman也完全可以)
结果:
请先
!