• Java 设计模式(上)


    目录

    一、单一职责原则

    二、开闭原则

    三、里氏替换原则

    四、迪米特法则

    五、接口隔离原则

    六、依赖倒置原则

    七、工厂方法

    八、抽象工厂

    九、建造者模式

    十、原型模式

    十一、单例模式

    十二、适配器模式


    一、单一职责原则

    单一职责原则又称单一功能原则,面向对象五基本原则之一。

    单一职责原则定义:一个对象应该只包含单一的职责,并且该职责被完整地封装在一个类中。

    错误示范:

    1. public class VideoUserService {
    2. public void serveGrade(String userType){
    3. if ("VIP用户".equals(userType)){
    4. System.out.println("VIP用户,视频1080P蓝光");
    5. } else if ("普通用户".equals(userType)){
    6. System.out.println("普通用户,视频720P超清");
    7. } else if ("访客用户".equals(userType)){
    8. System.out.println("访客用户,视频480P高清");
    9. }
    10. }
    11. }
    1. @Test
    2. void singleton() {
    3. VideoUserService service = new VideoUserService();
    4. service.serveGrade("VIP用户");
    5. service.serveGrade("普通用户");
    6. service.serveGrade("访客用户");
    7. }

    正确代码

    定义一个接口,分别来一个他们的子实现类

    1. public interface IVideoUserService {
    2. void definition();
    3. void advertisement();
    4. }
    1. public class VipVideoUserService implements IVideoUserService {
    2. public void definition() {
    3. System.out.println("VIP用户,视频1080P蓝光");
    4. }
    5. public void advertisement() {
    6. System.out.println("VIP会员,视频无广告");
    7. }
    8. }
    1. public class OrdinaryVideoUserService implements IVideoUserService {
    2. public void definition() {
    3. System.out.println("普通用户,视频720P超清");
    4. }
    5. public void advertisement() {
    6. System.out.println("普通用户,视频有广告");
    7. }
    8. }
    1. public class GuestVideoUserService implements IVideoUserService {
    2. public void definition() {
    3. System.out.println("访客用户,视频480P高清");
    4. }
    5. public void advertisement() {
    6. System.out.println("访客用户,视频有广告");
    7. }
    8. }
    1. void singleton02() {
    2. IVideoUserService guest = new GuestVideoUserService();
    3. guest.advertisement();
    4. guest.definition();
    5. }

    二、开闭原则

    开闭原则是:规定软件中的对象(其中包括类,模块,函数等等)应该对于扩展是开放的,但是对于修改是封闭的。

    举个例子,我么要求圆的面积,π的大概值为3.14,第一个人需要3.14,第二个人想要更加精确,但是又不能动第一个人的数据,所以对自己的进行扩展,代码如下

    接口

    1. public interface ICalculationArea {
    2. /**
    3. * 计算面积,长方形
    4. *
    5. * @param x 长
    6. * @param y 宽
    7. * @return 面积
    8. */
    9. double rectangle(double x, double y);
    10. /**
    11. * 计算面积,三角形
    12. * @param x 边长x
    13. * @param y 边长y
    14. * @param z 边长z
    15. * @return 面积
    16. *
    17. * 海伦公式:S=√[p(p-a)(p-b)(p-c)] 其中:p=(a+b+c)/2
    18. */
    19. double triangle(double x, double y, double z);
    20. /**
    21. * 计算面积,圆形
    22. * @param r 半径
    23. * @return 面积
    24. *
    25. * 圆面积公式:S=πr²
    26. */
    27. double circular(double r);
    28. }

    第一个人的需求

    1. public class CalculationArea implements ICalculationArea {
    2. private final static double π = 3.14D;
    3. public double rectangle(double x, double y) {
    4. return x * y;
    5. }
    6. public double triangle(double x, double y, double z) {
    7. double p = (x + y + z) / 2;
    8. return Math.sqrt(p * (p - x) * (p - y) * (p - z));
    9. }
    10. public double circular(double r) {
    11. return π * r * r;
    12. }
    13. }

    第二个人的需求

    1. public class CalculationAreaExt extends CalculationArea {
    2. private final static double π = 3.141592653D;
    3. @Override
    4. public double circular(double r) {
    5. return π * r * r;
    6. }
    7. }

    测试

    1. @Test
    2. void openClose01() {
    3. ICalculationArea area = new CalculationAreaExt();
    4. double circular = area.circular(10);
    5. System.out.println(circular);
    6. }

    三、里氏替换原则

    里氏替换原则,继承必须确保超类所拥有的性质在子类中依然成立。可以理解为,一个同名不同地方的餐馆,他的营销模式或者内容要一致,可以替换的,而不是风格全变了。

    1. public abstract class BankCard {
    2. private Logger logger = LoggerFactory.getLogger(BankCard.class);
    3. private String cardNo; // 卡号
    4. private String cardDate; // 开卡时间
    5. public BankCard(String cardNo, String cardDate) {
    6. this.cardNo = cardNo;
    7. this.cardDate = cardDate;
    8. }
    9. abstract boolean rule(BigDecimal amount);
    10. // 正向入账,+ 钱
    11. public String positive(String orderId, BigDecimal amount) {
    12. // 入款成功,存款、还款
    13. logger.info("卡号{} 入款成功,单号:{} 金额:{}", cardNo, orderId, amount);
    14. return "0000";
    15. }
    16. // 逆向入账,- 钱
    17. public String negative(String orderId, BigDecimal amount) {
    18. // 入款成功,存款、还款
    19. logger.info("卡号{} 出款成功,单号:{} 金额:{}", cardNo, orderId, amount);
    20. return "0000";
    21. }
    22. /**
    23. * 交易流水查询
    24. *
    25. * @return 交易流水
    26. */
    27. public List tradeFlow() {
    28. logger.info("交易流水查询成功");
    29. List tradeList = new ArrayList();
    30. tradeList.add("100001,100.00");
    31. tradeList.add("100001,80.00");
    32. tradeList.add("100001,76.50");
    33. tradeList.add("100001,126.00");
    34. return tradeList;
    35. }
    36. public String getCardNo() {
    37. return cardNo;
    38. }
    39. public String getCardDate() {
    40. return cardDate;
    41. }
    42. }
    1. public class CashCard extends BankCard {
    2. private Logger logger = LoggerFactory.getLogger(CashCard.class);
    3. public CashCard(String cardNo, String cardDate) {
    4. super(cardNo, cardDate);
    5. }
    6. boolean rule(BigDecimal amount) {
    7. return true;
    8. }
    9. /**
    10. * 提现
    11. *
    12. * @param orderId 单号
    13. * @param amount 金额
    14. * @return 状态码 0000成功、0001失败、0002重复
    15. */
    16. public String withdrawal(String orderId, BigDecimal amount) {
    17. // 模拟支付成功
    18. logger.info("提现成功,单号:{} 金额:{}", orderId, amount);
    19. return super.negative(orderId, amount);
    20. }
    21. /**
    22. * 储蓄
    23. *
    24. * @param orderId 单号
    25. * @param amount 金额
    26. */
    27. public String recharge(String orderId, BigDecimal amount) {
    28. // 模拟充值成功
    29. logger.info("储蓄成功,单号:{} 金额:{}", orderId, amount);
    30. return super.positive(orderId, amount);
    31. }
    32. /**
    33. * 风险校验
    34. *
    35. * @param cardNo 卡号
    36. * @param orderId 单号
    37. * @param amount 金额
    38. * @return 状态
    39. */
    40. public boolean checkRisk(String cardNo, String orderId, BigDecimal amount) {
    41. // 模拟风控校验
    42. logger.info("风控校验,卡号:{} 单号:{} 金额:{}", cardNo, orderId, amount);
    43. return true;
    44. }
    45. }
    1. public class CreditCard extends CashCard {
    2. private Logger logger = LoggerFactory.getLogger(CreditCard.class);
    3. public CreditCard(String cardNo, String cardDate) {
    4. super(cardNo, cardDate);
    5. }
    6. boolean rule2(BigDecimal amount) {
    7. return amount.compareTo(new BigDecimal(1000)) <= 0;
    8. }
    9. /**
    10. * 提现,信用卡贷款
    11. *
    12. * @param orderId 单号
    13. * @param amount 金额
    14. * @return 状态码
    15. */
    16. public String loan(String orderId, BigDecimal amount) {
    17. boolean rule = rule2(amount);
    18. if (!rule) {
    19. logger.info("生成贷款单失败,金额超限。单号:{} 金额:{}", orderId, amount);
    20. return "0001";
    21. }
    22. // 模拟生成贷款单
    23. logger.info("生成贷款单,单号:{} 金额:{}", orderId, amount);
    24. // 模拟支付成功
    25. logger.info("贷款成功,单号:{} 金额:{}", orderId, amount);
    26. return super.negative(orderId, amount);
    27. }
    28. /**
    29. * 还款,信用卡还款
    30. *
    31. * @param orderId 单号
    32. * @param amount 金额
    33. * @return 状态码
    34. */
    35. public String repayment(String orderId, BigDecimal amount) {
    36. // 模拟生成还款单
    37. logger.info("生成还款单,单号:{} 金额:{}", orderId, amount);
    38. // 模拟还款成功
    39. logger.info("还款成功,单号:{} 金额:{}", orderId, amount);
    40. return super.positive(orderId, amount);
    41. }
    42. }
    1. @Test
    2. void replace01() {
    3. logger.info("里氏替换前,CashCard类:");
    4. CashCard bankCard = new CashCard("6214567800989876", "2022-03-05");
    5. // 提现
    6. bankCard.withdrawal("100001", new BigDecimal(100));
    7. // 储蓄
    8. bankCard.recharge("100001", new BigDecimal(100));
    9. logger.info("里氏替换后,CreditCard类:");
    10. CashCard creditCard = new CreditCard("6214567800989876", "2022-03-05");
    11. // 提现
    12. creditCard.withdrawal("100001", new BigDecimal(1000000));
    13. // 储蓄
    14. creditCard.recharge("100001", new BigDecimal(100));
    15. }
    16. @Test
    17. void replace02() {
    18. CreditCard creditCard = new CreditCard("6214567800989876", "2022-03-05");
    19. // 支付,贷款
    20. creditCard.loan("100001", new BigDecimal(100));
    21. // 还款
    22. creditCard.repayment("100001", new BigDecimal(100));
    23. }

    两张卡,做了同样的事情,结果是一致的,替换的方式是正确的。

    四、迪米特法则

    迪米特法则,意义在于降低类之间的耦合。由于每个对象尽量减少对其他对象的了解,因此,很容易使得系统的功能模块功能独立,相互之间不存在(或者有很少)依赖关系。也就是模块与模块之间最少知道,是单个模块能自己独立出来(高内聚,低耦合)。

    举个例子,校长、学生、老师,校长应该直接可以观察老师,老师观察学生,而不是校长直接观察学生,而是老师来提供信息给校长。

    1. public class Principal {
    2. private Teacher teacher = new Teacher("丽华", "3年1班");
    3. // 查询班级信息,总分数、学生人数、平均值
    4. public Map queryClazzInfo(String clazzId) {
    5. // 获取班级信息;学生总人数、总分、平均分
    6. int stuCount = teacher.clazzStudentCount();
    7. double totalScore = teacher.clazzTotalScore();
    8. double averageScore = teacher.clazzAverageScore();
    9. // 组装对象,实际业务开发会有对应的类
    10. Map mapObj = new HashMap<>();
    11. mapObj.put("班级", teacher.getClazz());
    12. mapObj.put("老师", teacher.getName());
    13. mapObj.put("学生人数", stuCount);
    14. mapObj.put("班级总分数", totalScore);
    15. mapObj.put("班级平均分", averageScore);
    16. return mapObj;
    17. }
    18. }
    1. public class Teacher {
    2. private String name; // 老师名称
    3. private String clazz; // 班级
    4. private static List studentList; // 学生
    5. public Teacher() {
    6. }
    7. public Teacher(String name, String clazz) {
    8. this.name = name;
    9. this.clazz = clazz;
    10. }
    11. static {
    12. studentList = new ArrayList<>();
    13. studentList.add(new Student("花花", 10, 589));
    14. studentList.add(new Student("豆豆", 54, 356));
    15. studentList.add(new Student("秋雅", 23, 439));
    16. studentList.add(new Student("皮皮", 2, 665));
    17. studentList.add(new Student("蛋蛋", 19, 502));
    18. }
    19. // 总分
    20. public double clazzTotalScore() {
    21. double totalScore = 0;
    22. for (Student stu : studentList) {
    23. totalScore += stu.getGrade();
    24. }
    25. return totalScore;
    26. }
    27. // 平均分
    28. public double clazzAverageScore(){
    29. double totalScore = 0;
    30. for (Student stu : studentList) {
    31. totalScore += stu.getGrade();
    32. }
    33. return totalScore / studentList.size();
    34. }
    35. // 班级人数
    36. public int clazzStudentCount(){
    37. return studentList.size();
    38. }
    39. public static List getStudentList() {
    40. return studentList;
    41. }
    42. public String getName() {
    43. return name;
    44. }
    45. public String getClazz() {
    46. return clazz;
    47. }
    48. }
    1. public class Student {
    2. private String name; // 学生姓名
    3. private int rank; // 考试排名(总排名)
    4. private double grade; // 考试分数(总分)
    5. public Student() {
    6. }
    7. public Student(String name, int rank, double grade) {
    8. this.name = name;
    9. this.rank = rank;
    10. this.grade = grade;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public int getRank() {
    19. return rank;
    20. }
    21. public void setRank(int rank) {
    22. this.rank = rank;
    23. }
    24. public double getGrade() {
    25. return grade;
    26. }
    27. public void setGrade(double grade) {
    28. this.grade = grade;
    29. }
    30. }
    1. @Test
    2. void dimite() {
    3. Principal principal = new Principal();
    4. Map map = principal.queryClazzInfo("3年1班");
    5. logger.info("查询结果:{}", JSON.toJSONString(map));
    6. }

    五、接口隔离原则

    要求 程序员尽量将臃肿庞大的接口拆分为更小的和更具体的接口,让接口中只包含客户感兴趣的方法。更小的接口,更具体的接口(高内聚,低耦合)。

    1. public interface ISkillArchery {
    2. // 射箭
    3. void doArchery();
    4. }
    1. public interface ISkillInvisible {
    2. // 隐袭
    3. void doInvisible();
    4. }
    1. public interface ISkillSilent {
    2. // 沉默
    3. void doSilent();
    4. }
    1. public interface ISkillVertigo {
    2. // 眩晕
    3. void doVertigo();
    4. }
    1. // 后裔
    2. public class HeroHouYi implements ISkillArchery, ISkillInvisible, ISkillSilent {
    3. @Override
    4. public void doArchery() {
    5. System.out.println("后裔的灼日之矢");
    6. }
    7. @Override
    8. public void doInvisible() {
    9. System.out.println("后裔的隐身技能");
    10. }
    11. @Override
    12. public void doSilent() {
    13. System.out.println("后裔的沉默技能");
    14. }
    15. }
    1. // 廉颇
    2. public class HeroLianPo implements ISkillInvisible, ISkillSilent, ISkillVertigo {
    3. @Override
    4. public void doInvisible() {
    5. System.out.println("廉颇的隐身技能");
    6. }
    7. @Override
    8. public void doSilent() {
    9. System.out.println("廉颇的沉默技能");
    10. }
    11. @Override
    12. public void doVertigo() {
    13. System.out.println("廉颇的眩晕技能");
    14. }
    15. }
    1. @Test
    2. public void InterfaceSegregation(){
    3. // 后裔
    4. HeroHouYi heroHouYi = new HeroHouYi();
    5. heroHouYi.doArchery();
    6. // 廉颇
    7. HeroLianPo heroLianPo = new HeroLianPo();
    8. heroLianPo.doInvisible();
    9. }

    六、依赖倒置原则

    高层模块不应该依赖低层模块,两者都应该依赖其抽象;抽象不应该依赖细节,细节应该依赖抽象(依赖接口,降低耦合),简单来说就是要求对抽象进行编程,不要对实现进行编程。其核心思想是:要面向接口编程,不要面向实现编程。依赖倒置原则是实现开闭原则的重要途径之一,它降低了客户与实现模块之间的耦合。

    举个例子:上级给下级颁布任务,不可能是上级走到下级面前告诉他要完成xx任务,如果有n个下级,那上级就要走n次,这显然是不可能的,这时,我上级定义了一个标准,下级只需要按照这个标准提交任务即可,这样形成了一个依赖倒置。

    1. // 抽奖接口
    2. public interface IDraw {
    3. List prize(List list, int count);
    4. }
    1. // 用户
    2. public class BetUser {
    3. private String userName; // 用户姓名
    4. private int userWeight; // 用户权重
    5. public BetUser() {
    6. }
    7. public BetUser(String userName, int userWeight) {
    8. this.userName = userName;
    9. this.userWeight = userWeight;
    10. }
    11. public String getUserName() {
    12. return userName;
    13. }
    14. public void setUserName(String userName) {
    15. this.userName = userName;
    16. }
    17. public int getUserWeight() {
    18. return userWeight;
    19. }
    20. public void setUserWeight(int userWeight) {
    21. this.userWeight = userWeight;
    22. }
    23. }
    1. // 抽奖控制
    2. public class DrawControl {
    3. private IDraw draw;
    4. public List doDraw(IDraw draw, List betUserList, int count) {
    5. return draw.prize(betUserList, count);
    6. }
    7. }
    1. // 随机抽奖
    2. public class DrawRandom implements IDraw {
    3. @Override
    4. public List prize(List list, int count) {
    5. // 集合数量很小直接返回
    6. if (list.size() <= count) return list;
    7. // 乱序集合
    8. Collections.shuffle(list);
    9. // 取出指定数量的中奖用户
    10. List prizeList = new ArrayList<>(count);
    11. for (int i = 0; i < count; i++) {
    12. prizeList.add(list.get(i));
    13. }
    14. return prizeList;
    15. }
    16. }
    1. public class DrawWeightRank implements IDraw {
    2. @Override
    3. public List prize(List list, int count) {
    4. // 按照权重排序
    5. list.sort((o1, o2) -> {
    6. int e = o2.getUserWeight() - o1.getUserWeight();
    7. if (0 == e) return 0;
    8. return e > 0 ? 1 : -1;
    9. });
    10. // 取出指定数量的中奖用户
    11. List prizeList = new ArrayList<>(count);
    12. for (int i = 0; i < count; i++) {
    13. prizeList.add(list.get(i));
    14. }
    15. return prizeList;
    16. }
    17. }
    1. @Test
    2. public void DependencyInversion() {
    3. List betUserList = new ArrayList<>();
    4. betUserList.add(new BetUser("花花", 65));
    5. betUserList.add(new BetUser("豆豆", 43));
    6. betUserList.add(new BetUser("小白", 72));
    7. betUserList.add(new BetUser("笨笨", 89));
    8. betUserList.add(new BetUser("丑蛋", 10));
    9. DrawControl drawControl = new DrawControl();
    10. List prizeRandomUserList = drawControl.doDraw(new DrawRandom(), betUserList, 3);
    11. logger.info("随机抽奖,中奖用户名单:{}", JSON.toJSON(prizeRandomUserList));
    12. List prizeWeightUserList = drawControl.doDraw(new DrawWeightRank(), betUserList, 3);
    13. logger.info("权重抽奖,中奖用户名单:{}", JSON.toJSON(prizeWeightUserList));
    14. }

    七、工厂方法

    工厂模式又称工厂方法模式,是一种创建型设计模式,其在父类中提供一个创建对象的方法, 允许子类决定实例化对象的类型。

    这种设计模式也是 Java 开发中最常见的一种模式,它的主要意图是定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。

    简单说就是为了提供代码结构的扩展性,屏蔽每一个功能类中的具体实现逻辑。让外部可以更加简单的只是知道调用即可,同时,这也是去掉众多ifelse的方式。当然这可能也有一些缺点,比如需要实现的类非常多,如何去维护,怎样减低开发成本。但这些问题都可以在后续的设计模式结合使用中,逐步降低。

    1. public interface ICommodity {
    2. void sendCommodity(String uId, String commodityId, String bizId, Map extMap) throws Exception;
    3. }
    1. // 工厂
    2. public class StoreFactory {
    3. /**
    4. * 奖品类型方式实例化
    5. * @param commodityType 奖品类型
    6. * @return 实例化对象
    7. */
    8. public ICommodity getCommodityService(Integer commodityType) {
    9. if (null == commodityType) return null;
    10. if (1 == commodityType) return new CouponCommodityService();
    11. if (2 == commodityType) return new GoodsCommodityService();
    12. if (3 == commodityType) return new CardCommodityService();
    13. throw new RuntimeException("不存在的奖品服务类型");
    14. }
    15. /**
    16. * 奖品类信息方式实例化
    17. * @param clazz 奖品类
    18. * @return 实例化对象
    19. */
    20. public ICommodity getCommodityService(Class clazz) throws IllegalAccessException, InstantiationException {
    21. if (null == clazz) return null;
    22. return clazz.newInstance();
    23. }
    24. }
    1. public class CardCommodityService implements ICommodity {
    2. private Logger logger = LoggerFactory.getLogger(CardCommodityService.class);
    3. // 模拟注入
    4. private IQiYiCardService iQiYiCardService = new IQiYiCardService();
    5. public void sendCommodity(String uId, String commodityId, String bizId, Map extMap) throws Exception {
    6. String mobile = queryUserMobile(uId);
    7. iQiYiCardService.grantToken(mobile, bizId);
    8. logger.info("请求参数[爱奇艺兑换卡] => uId:{} commodityId:{} bizId:{} extMap:{}", uId, commodityId, bizId, JSON.toJSON(extMap));
    9. logger.info("测试结果[爱奇艺兑换卡]:success");
    10. }
    11. private String queryUserMobile(String uId) {
    12. return "15200101232";
    13. }
    14. }
    1. public class CouponCommodityService implements ICommodity {
    2. private Logger logger = LoggerFactory.getLogger(CouponCommodityService.class);
    3. private CouponService couponService = new CouponService();
    4. public void sendCommodity(String uId, String commodityId, String bizId, Map extMap) throws Exception {
    5. CouponResult couponResult = couponService.sendCoupon(uId, commodityId, bizId);
    6. logger.info("请求参数[优惠券] => uId:{} commodityId:{} bizId:{} extMap:{}", uId, commodityId, bizId, JSON.toJSON(extMap));
    7. logger.info("测试结果[优惠券]:{}", JSON.toJSON(couponResult));
    8. if (!"0000".equals(couponResult.getCode())) throw new RuntimeException(couponResult.getInfo());
    9. }
    10. }
    1. public class GoodsCommodityService implements ICommodity {
    2. private Logger logger = LoggerFactory.getLogger(GoodsCommodityService.class);
    3. private GoodsService goodsService = new GoodsService();
    4. public void sendCommodity(String uId, String commodityId, String bizId, Map extMap) throws Exception {
    5. DeliverReq deliverReq = new DeliverReq();
    6. deliverReq.setUserName(queryUserName(uId));
    7. deliverReq.setUserPhone(queryUserPhoneNumber(uId));
    8. deliverReq.setSku(commodityId);
    9. deliverReq.setOrderId(bizId);
    10. deliverReq.setConsigneeUserName(extMap.get("consigneeUserName"));
    11. deliverReq.setConsigneeUserPhone(extMap.get("consigneeUserPhone"));
    12. deliverReq.setConsigneeUserAddress(extMap.get("consigneeUserAddress"));
    13. Boolean isSuccess = goodsService.deliverGoods(deliverReq);
    14. logger.info("请求参数[实物商品] => uId:{} commodityId:{} bizId:{} extMap:{}", uId, commodityId, bizId, JSON.toJSON(extMap));
    15. logger.info("测试结果[实物商品]:{}", isSuccess);
    16. if (!isSuccess) throw new RuntimeException("实物商品发放失败");
    17. }
    18. private String queryUserName(String uId) {
    19. return "花花";
    20. }
    21. private String queryUserPhoneNumber(String uId) {
    22. return "15200101232";
    23. }
    24. }
    1. @Test
    2. public void FactoryMethod01() throws Exception {
    3. StoreFactory storeFactory = new StoreFactory();
    4. // 1. 优惠券
    5. ICommodity commodityService_1 = storeFactory.getCommodityService(1);
    6. commodityService_1.sendCommodity("10001", "EGM1023938910232121323432", "791098764902132", null);
    7. // 2. 实物商品
    8. ICommodity commodityService_2 = storeFactory.getCommodityService(2);
    9. commodityService_2.sendCommodity("10001", "9820198721311", "1023000020112221113", new HashMap() {{
    10. put("consigneeUserName", "谢飞机");
    11. put("consigneeUserPhone", "15200292123");
    12. put("consigneeUserAddress", "吉林省.长春市.双阳区.XX街道.檀溪苑小区.#18-2109");
    13. }});
    14. // 3. 第三方兑换卡(模拟爱奇艺)
    15. ICommodity commodityService_3 = storeFactory.getCommodityService(3);
    16. commodityService_3.sendCommodity("10001", "AQY1xjkUodl8LO975GdfrYUio", null, null);
    17. }

    1. @Test
    2. public void FactoryMethod02() throws Exception {
    3. StoreFactory storeFactory = new StoreFactory();
    4. // 1. 优惠券
    5. ICommodity commodityService = storeFactory.getCommodityService(CouponCommodityService.class);
    6. commodityService.sendCommodity("10001", "EGM1023938910232121323432", "791098764902132", null);
    7. }

    八、抽象工厂

    抽象工厂模式与工厂方法模式虽然主要意图都是为了解决,接口选择问题。但在实现上,抽象工厂是一个中心工厂,创建其他工厂的模式。

    1. @Test
    2. public void AbstractFactory() throws Exception {
    3. CacheService proxy_EGM = JDKProxyFactory.getProxy(CacheService.class, EGMCacheAdapter.class);
    4. proxy_EGM.set("user_name_01", "xxx");
    5. String val01 = proxy_EGM.get("user_name_01");
    6. logger.info("缓存服务 EGM 测试,proxy_EGM.get 测试结果:{}", val01);
    7. CacheService proxy_IIR = JDKProxyFactory.getProxy(CacheService.class, IIRCacheAdapter.class);
    8. proxy_IIR.set("user_name_01", "yyy");
    9. String val02 = proxy_IIR.get("user_name_01");
    10. logger.info("缓存服务 IIR 测试,proxy_IIR.get 测试结果:{}", val02);
    11. }
    1. public class JDKProxyFactory {
    2. public static T getProxy(Class cacheClazz, Class cacheAdapter) throws Exception {
    3. InvocationHandler handler = new JDKInvocationHandler(cacheAdapter.newInstance());
    4. ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    5. return (T) Proxy.newProxyInstance(classLoader, new Class[]{cacheClazz}, handler);
    6. }
    7. }
    1. public class JDKInvocationHandler implements InvocationHandler {
    2. private ICacheAdapter cacheAdapter;
    3. public JDKInvocationHandler(ICacheAdapter cacheAdapter) {
    4. this.cacheAdapter = cacheAdapter;
    5. }
    6. @Override
    7. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    8. return ICacheAdapter.class.getMethod(method.getName(), ClassLoaderUtils.getClazzByArgs(args)).invoke(cacheAdapter, args);
    9. }
    10. }
    1. public interface ICacheAdapter {
    2. String get(final String key);
    3. void set(String key, String value);
    4. void set(String key, String value, long timeout, TimeUnit timeUnit);
    5. void del(String key);
    6. }
    1. public class IIRCacheAdapter implements ICacheAdapter {
    2. private IIR iir = new IIR();
    3. @Override
    4. public String get(String key) {
    5. return iir.get(key);
    6. }
    7. @Override
    8. public void set(String key, String value) {
    9. iir.set(key, value);
    10. }
    11. @Override
    12. public void set(String key, String value, long timeout, TimeUnit timeUnit) {
    13. iir.setExpire(key, value, timeout, timeUnit);
    14. }
    15. @Override
    16. public void del(String key) {
    17. iir.del(key);
    18. }
    19. }
    1. public class EGMCacheAdapter implements ICacheAdapter {
    2. private EGM egm = new EGM();
    3. public String get(String key) {
    4. return egm.gain(key);
    5. }
    6. public void set(String key, String value) {
    7. egm.set(key, value);
    8. }
    9. public void set(String key, String value, long timeout, TimeUnit timeUnit) {
    10. egm.setEx(key, value, timeout, timeUnit);
    11. }
    12. public void del(String key) {
    13. egm.delete(key);
    14. }
    15. }

    九、建造者模式

    建造者模式所完成的内容就是通过将多个简单对象通过一步步的组装构建出一个复杂对象的过程。

    而这样的根据相同的物料,不同的组装所产生出的具体的内容,就是建造者模式的最终意图,也就是;将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。

    1. @Test
    2. public void test_Builder(){
    3. Builder builder = new Builder();
    4. // 豪华欧式
    5. System.out.println(builder.levelOne(132.52D).getDetail());
    6. // 轻奢田园
    7. System.out.println(builder.levelTwo(98.25D).getDetail());
    8. // 现代简约
    9. System.out.println(builder.levelThree(85.43D).getDetail());
    10. }
    1. public class Builder {
    2. public IMenu levelOne(Double area) {
    3. return new DecorationPackageMenu(area, "豪华欧式")
    4. .appendCeiling(new LevelTwoCeiling()) // 吊顶,二级顶
    5. .appendCoat(new DuluxCoat()) // 涂料,多乐士
    6. .appendFloor(new ShengXiangFloor()); // 地板,圣象
    7. }
    8. public IMenu levelTwo(Double area){
    9. return new DecorationPackageMenu(area, "轻奢田园")
    10. .appendCeiling(new LevelTwoCeiling()) // 吊顶,二级顶
    11. .appendCoat(new LiBangCoat()) // 涂料,立邦
    12. .appendTile(new MarcoPoloTile()); // 地砖,马可波罗
    13. }
    14. public IMenu levelThree(Double area){
    15. return new DecorationPackageMenu(area, "现代简约")
    16. .appendCeiling(new LevelOneCeiling()) // 吊顶,一级顶
    17. .appendCoat(new LiBangCoat()) // 涂料,立邦
    18. .appendTile(new DongPengTile()); // 地砖,东鹏
    19. }
    20. }
    1. public interface IMenu {
    2. /**
    3. * 吊顶
    4. */
    5. IMenu appendCeiling(Matter matter);
    6. /**
    7. * 涂料
    8. */
    9. IMenu appendCoat(Matter matter);
    10. /**
    11. * 地板
    12. */
    13. IMenu appendFloor(Matter matter);
    14. /**
    15. * 地砖
    16. */
    17. IMenu appendTile(Matter matter);
    18. /**
    19. * 明细
    20. */
    21. String getDetail();
    22. }
    1. public interface Matter {
    2. /**
    3. * 场景;地板、地砖、涂料、吊顶
    4. */
    5. String scene();
    6. /**
    7. * 品牌
    8. */
    9. String brand();
    10. /**
    11. * 型号
    12. */
    13. String model();
    14. /**
    15. * 平米报价
    16. */
    17. BigDecimal price();
    18. /**
    19. * 描述
    20. */
    21. String desc();
    22. }
    1. // 装修包
    2. public class DecorationPackageMenu implements IMenu {
    3. private List list = new ArrayList(); // 装修清单
    4. private BigDecimal price = BigDecimal.ZERO; // 装修价格
    5. private BigDecimal area; // 面积
    6. private String grade; // 装修等级;豪华欧式、轻奢田园、现代简约
    7. private DecorationPackageMenu() {
    8. }
    9. public DecorationPackageMenu(Double area, String grade) {
    10. this.area = new BigDecimal(area);
    11. this.grade = grade;
    12. }
    13. public IMenu appendCeiling(Matter matter) {
    14. list.add(matter);
    15. price = price.add(area.multiply(new BigDecimal("0.2")).multiply(matter.price()));
    16. return this;
    17. }
    18. public IMenu appendCoat(Matter matter) {
    19. list.add(matter);
    20. price = price.add(area.multiply(new BigDecimal("1.4")).multiply(matter.price()));
    21. return this;
    22. }
    23. public IMenu appendFloor(Matter matter) {
    24. list.add(matter);
    25. price = price.add(area.multiply(matter.price()));
    26. return this;
    27. }
    28. public IMenu appendTile(Matter matter) {
    29. list.add(matter);
    30. price = price.add(area.multiply(matter.price()));
    31. return this;
    32. }
    33. public String getDetail() {
    34. StringBuilder detail = new StringBuilder("\r\n-------------------------------------------------------\r\n" +
    35. "装修清单" + "\r\n" +
    36. "套餐等级:" + grade + "\r\n" +
    37. "套餐价格:" + price.setScale(2, BigDecimal.ROUND_HALF_UP) + " 元\r\n" +
    38. "房屋面积:" + area.doubleValue() + " 平米\r\n" +
    39. "材料清单:\r\n");
    40. for (Matter matter: list) {
    41. detail.append(matter.scene()).append(":").append(matter.brand()).append("、").append(matter.model()).append("、平米价格:").append(matter.price()).append(" 元。\n");
    42. }
    43. return detail.toString();
    44. }
    45. }

    十、原型模式

    原型模式主要解决的问题就是创建重复对象,而这部分对象内容本身比较复杂,生成过程可能从库或者RPC接口中获取数据的耗时较长,因此采用克隆的方式节省时间。

    举个例子,一场考试在保证大家的公平性一样的题目下,开始出现试题混排更有做的好的答案选项也混排。这样大大的增加了抄的成本,也更好的做到了考试的公平性。

    1. @Test
    2. public void prototype() throws CloneNotSupportedException {
    3. QuestionBankController questionBankController = new QuestionBankController();
    4. System.out.println(questionBankController.createPaper("花花", "1000001921032"));
    5. System.out.println(questionBankController.createPaper("豆豆", "1000001921051"));
    6. System.out.println(questionBankController.createPaper("大宝", "1000001921987"));
    7. }
    1. // 题库管理
    2. public class QuestionBankController {
    3. private QuestionBank questionBank = new QuestionBank();
    4. public QuestionBankController() {
    5. questionBank.append(new ChoiceQuestion("JAVA所定义的版本中不包括", new HashMap() {{
    6. put("A", "JAVA2 EE");
    7. put("B", "JAVA2 Card");
    8. put("C", "JAVA2 ME");
    9. put("D", "JAVA2 HE");
    10. put("E", "JAVA2 SE");
    11. }}, "D")).append(new ChoiceQuestion("下列说法正确的是", new HashMap() {{
    12. put("A", "JAVA程序的main方法必须写在类里面");
    13. put("B", "JAVA程序中可以有多个main方法");
    14. put("C", "JAVA程序中类名必须与文件名一样");
    15. put("D", "JAVA程序的main方法中如果只有一条语句,可以不用{}(大括号)括起来");
    16. }}, "A")).append(new ChoiceQuestion("变量命名规范说法正确的是", new HashMap() {{
    17. put("A", "变量由字母、下划线、数字、$符号随意组成;");
    18. put("B", "变量不能以数字作为开头;");
    19. put("C", "A和a在java中是同一个变量;");
    20. put("D", "不同类型的变量,可以起相同的名字;");
    21. }}, "B")).append(new ChoiceQuestion("以下()不是合法的标识符", new HashMap() {{
    22. put("A", "STRING");
    23. put("B", "x3x;");
    24. put("C", "void");
    25. put("D", "de$f");
    26. }}, "C")).append(new ChoiceQuestion("表达式(11+3*8)/4%3的值是", new HashMap() {{
    27. put("A", "31");
    28. put("B", "0");
    29. put("C", "1");
    30. put("D", "2");
    31. }}, "D"))
    32. .append(new AnswerQuestion("小红马和小黑马生的小马几条腿", "4条腿"))
    33. .append(new AnswerQuestion("铁棒打头疼还是木棒打头疼", "头最疼"))
    34. .append(new AnswerQuestion("什么床不能睡觉", "牙床"))
    35. .append(new AnswerQuestion("为什么好马不吃回头草", "后面的草没了"));
    36. }
    37. public String createPaper(String candidate, String number) throws CloneNotSupportedException {
    38. QuestionBank questionBankClone = (QuestionBank) questionBank.clone();
    39. questionBankClone.setCandidate(candidate);
    40. questionBankClone.setNumber(number);
    41. return questionBankClone.toString();
    42. }
    43. }
    1. // 题库
    2. public class QuestionBank implements Cloneable{
    3. private String candidate; // 考生
    4. private String number; // 考号
    5. private ArrayList choiceQuestionList = new ArrayList<>();
    6. private ArrayList answerQuestionList = new ArrayList<>();
    7. public QuestionBank append(ChoiceQuestion choiceQuestion) {
    8. choiceQuestionList.add(choiceQuestion);
    9. return this;
    10. }
    11. public QuestionBank append(AnswerQuestion answerQuestion) {
    12. answerQuestionList.add(answerQuestion);
    13. return this;
    14. }
    15. @Override
    16. public Object clone() throws CloneNotSupportedException {
    17. QuestionBank questionBank = (QuestionBank) super.clone();
    18. questionBank.choiceQuestionList = (ArrayList) choiceQuestionList.clone();
    19. questionBank.answerQuestionList = (ArrayList) answerQuestionList.clone();
    20. // 题目乱序
    21. Collections.shuffle(questionBank.choiceQuestionList);
    22. Collections.shuffle(questionBank.answerQuestionList);
    23. // 答案乱序
    24. ArrayList choiceQuestionList = questionBank.choiceQuestionList;
    25. for (ChoiceQuestion question : choiceQuestionList) {
    26. Topic random = TopicRandomUtil.random(question.getOption(), question.getKey());
    27. question.setOption(random.getOption());
    28. question.setKey(random.getKey());
    29. }
    30. return questionBank;
    31. }
    32. public void setCandidate(String candidate) {
    33. this.candidate = candidate;
    34. }
    35. public void setNumber(String number) {
    36. this.number = number;
    37. }
    38. @Override
    39. public String toString() {
    40. StringBuilder detail = new StringBuilder("考生:" + candidate + "\r\n" +
    41. "考号:" + number + "\r\n" +
    42. "--------------------------------------------\r\n" +
    43. "一、选择题" + "\r\n\n");
    44. for (int idx = 0; idx < choiceQuestionList.size(); idx++) {
    45. detail.append("第").append(idx + 1).append("题:").append(choiceQuestionList.get(idx).getName()).append("\r\n");
    46. Map option = choiceQuestionList.get(idx).getOption();
    47. for (String key : option.keySet()) {
    48. detail.append(key).append(":").append(option.get(key)).append("\r\n");;
    49. }
    50. detail.append("答案:").append(choiceQuestionList.get(idx).getKey()).append("\r\n\n");
    51. }
    52. detail.append("二、问答题" + "\r\n\n");
    53. for (int idx = 0; idx < answerQuestionList.size(); idx++) {
    54. detail.append("第").append(idx + 1).append("题:").append(answerQuestionList.get(idx).getName()).append("\r\n");
    55. detail.append("答案:").append(answerQuestionList.get(idx).getKey()).append("\r\n\n");
    56. }
    57. return detail.toString();
    58. }
    59. }
    1. // 选择题
    2. public class ChoiceQuestion {
    3. private String name; // 题目
    4. private Map option; // 选项;A、B、C、D
    5. private String key; // 答案;B
    6. public ChoiceQuestion() {
    7. }
    8. public ChoiceQuestion(String name, Map option, String key) {
    9. this.name = name;
    10. this.option = option;
    11. this.key = key;
    12. }
    13. public String getName() {
    14. return name;
    15. }
    16. public void setName(String name) {
    17. this.name = name;
    18. }
    19. public Map getOption() {
    20. return option;
    21. }
    22. public void setOption(Map option) {
    23. this.option = option;
    24. }
    25. public String getKey() {
    26. return key;
    27. }
    28. public void setKey(String key) {
    29. this.key = key;
    30. }
    31. }
    1. // 解答题
    2. public class AnswerQuestion {
    3. private String name; // 问题
    4. private String key; // 答案
    5. public AnswerQuestion() {
    6. }
    7. public AnswerQuestion(String name, String key) {
    8. this.name = name;
    9. this.key = key;
    10. }
    11. public String getName() {
    12. return name;
    13. }
    14. public void setName(String name) {
    15. this.name = name;
    16. }
    17. public String getKey() {
    18. return key;
    19. }
    20. public void setKey(String key) {
    21. this.key = key;
    22. }
    23. }

    考生:花花
    考号:1000001921032
    --------------------------------------------
    一、选择题

    第1题:表达式(11+3*8)/4%3的值是
    A:2
    B:0
    C:31
    D:1
    答案:A

    第2题:变量命名规范说法正确的是
    A:变量不能以数字作为开头;
    B:不同类型的变量,可以起相同的名字;
    C:变量由字母、下划线、数字、$符号随意组成;
    D:A和a在java中是同一个变量;
    答案:A

    第3题:下列说法正确的是
    A:JAVA程序中类名必须与文件名一样
    B:JAVA程序的main方法必须写在类里面
    C:JAVA程序的main方法中如果只有一条语句,可以不用{}(大括号)括起来
    D:JAVA程序中可以有多个main方法
    答案:B

    第4题:以下()不是合法的标识符
    A:de$f
    B:void
    C:STRING
    D:x3x;
    答案:B

    第5题:JAVA所定义的版本中不包括
    A:JAVA2 HE
    B:JAVA2 EE
    C:JAVA2 SE
    D:JAVA2 ME
    E:JAVA2 Card
    答案:A

    二、问答题

    第1题:小红马和小黑马生的小马几条腿
    答案:4条腿

    第2题:为什么好马不吃回头草
    答案:后面的草没了

    第3题:铁棒打头疼还是木棒打头疼
    答案:头最疼

    第4题:什么床不能睡觉
    答案:牙床


    考生:豆豆
    考号:1000001921051
    --------------------------------------------
    一、选择题

    第1题:下列说法正确的是
    A:JAVA程序的main方法必须写在类里面
    B:JAVA程序中类名必须与文件名一样
    C:JAVA程序中可以有多个main方法
    D:JAVA程序的main方法中如果只有一条语句,可以不用{}(大括号)括起来
    答案:A

    第2题:以下()不是合法的标识符
    A:de$f
    B:STRING
    C:x3x;
    D:void
    答案:D

    第3题:表达式(11+3*8)/4%3的值是
    A:2
    B:0
    C:1
    D:31
    答案:A

    第4题:变量命名规范说法正确的是
    A:A和a在java中是同一个变量;
    B:变量不能以数字作为开头;
    C:不同类型的变量,可以起相同的名字;
    D:变量由字母、下划线、数字、$符号随意组成;
    答案:B

    第5题:JAVA所定义的版本中不包括
    A:JAVA2 Card
    B:JAVA2 EE
    C:JAVA2 HE
    D:JAVA2 ME
    E:JAVA2 SE
    答案:C

    二、问答题

    第1题:小红马和小黑马生的小马几条腿
    答案:4条腿

    第2题:为什么好马不吃回头草
    答案:后面的草没了

    第3题:铁棒打头疼还是木棒打头疼
    答案:头最疼

    第4题:什么床不能睡觉
    答案:牙床


    考生:大宝
    考号:1000001921987
    --------------------------------------------
    一、选择题

    第1题:以下()不是合法的标识符
    A:x3x;
    B:STRING
    C:de$f
    D:void
    答案:D

    第2题:JAVA所定义的版本中不包括
    A:JAVA2 ME
    B:JAVA2 EE
    C:JAVA2 HE
    D:JAVA2 SE
    E:JAVA2 Card
    答案:C

    第3题:变量命名规范说法正确的是
    A:变量由字母、下划线、数字、$符号随意组成;
    B:不同类型的变量,可以起相同的名字;
    C:A和a在java中是同一个变量;
    D:变量不能以数字作为开头;
    答案:D

    第4题:下列说法正确的是
    A:JAVA程序的main方法必须写在类里面
    B:JAVA程序中类名必须与文件名一样
    C:JAVA程序的main方法中如果只有一条语句,可以不用{}(大括号)括起来
    D:JAVA程序中可以有多个main方法
    答案:A

    第5题:表达式(11+3*8)/4%3的值是
    A:2
    B:1
    C:0
    D:31
    答案:A

    二、问答题

    第1题:小红马和小黑马生的小马几条腿
    答案:4条腿

    第2题:为什么好马不吃回头草
    答案:后面的草没了

    第3题:什么床不能睡觉
    答案:牙床

    第4题:铁棒打头疼还是木棒打头疼
    答案:头最疼

    十一、单例模式

    单例(Singleton)模式的定义:指一个类只有一个实例,且该类能自行创建这个实例的一种模式。例如,Windows 中只能打开一个任务管理器,这样可以避免因打开多个任务管理器窗口而造成内存资源的浪费,或出现各个窗口显示内容的不一致等错误。

    单例模式有 3 个特点:

    1. 单例类只有一个实例对象;
    2. 该单例对象必须由单例类自行创建;
    3. 单例类对外提供一个访问该单例的全局访问点;

    懒汉式单例

    该模式的特点是类加载时没有生成单例,只有当第一次调用 getlnstance 方法时才去创建这个单例。代码如下:

    1. public class LazySingleton
    2. {
    3. private static volatile LazySingleton instance=null; //保证 instance 在所有线程中同步
    4. private LazySingleton(){} //private 避免类在外部被实例化
    5. public static synchronized LazySingleton getInstance()
    6. {
    7. //getInstance 方法前加同步
    8. if(instance==null)
    9. {
    10. instance=new LazySingleton();
    11. }
    12. return instance;
    13. }
    14. }

     饿汉式单例

    该模式的特点是类一旦加载就创建一个单例,保证在调用 getInstance 方法之前单例已经存在了。

    1. public class HungrySingleton
    2. {
    3. private static final HungrySingleton instance=new HungrySingleton();
    4. private HungrySingleton(){}
    5. public static HungrySingleton getInstance()
    6. {
    7. return instance;
    8. }
    9. }

    饿汉式单例在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以是线程安全的,可以直接用于多线程而不会出现问题。

    应用实例

    用懒汉式单例模式模拟产生美国当今总统对象。

    1. public class SingletonLazy
    2. {
    3. public static void main(String[] args)
    4. {
    5. President zt1=President.getInstance();
    6. zt1.getName(); //输出总统的名字
    7. President zt2=President.getInstance();
    8. zt2.getName(); //输出总统的名字
    9. if(zt1==zt2)
    10. {
    11. System.out.println("他们是同一人!");
    12. }
    13. else
    14. {
    15. System.out.println("他们不是同一人!");
    16. }
    17. }
    18. }
    19. class President
    20. {
    21. private static volatile President instance=null; //保证instance在所有线程中同步
    22. //private避免类在外部被实例化
    23. private President()
    24. {
    25. System.out.println("产生一个总统!");
    26. }
    27. public static synchronized President getInstance()
    28. {
    29. //在getInstance方法上加同步
    30. if(instance==null)
    31. {
    32. instance=new President();
    33. }
    34. else
    35. {
    36. System.out.println("已经有一个总统,不能产生新总统!");
    37. }
    38. return instance;
    39. }
    40. public void getName()
    41. {
    42. System.out.println("我是美国总统:特朗普。");
    43. }
    44. }
    产生一个总统!
    我是美国总统:特朗普。
    已经有一个总统,不能产生新总统!
    我是美国总统:特朗普。
    他们是同一人!
    

    单例模式的应用场景

    以下是它通常适用的场景的特点。

    在应用场景中,某类只要求生成一个对象的时候,如一个班中的班长、每个人的身份证号等。

    当对象需要被共享的场合。由于单例模式只允许创建一个对象,共享该对象可以节省内存,并加快对象访问速度。如 Web 中的配置对象、数据库的连接池等。

    当某类需要频繁实例化,而创建的对象又频繁被销毁的时候,如多线程的线程池、网络连接池等。

    十二、适配器模式

    适配器模式(Adapter Pattern)将某个类的接口转换成客户端期望的另一个接口表示,主的目的是兼容性,让原本因接口不匹配不能一起工作的两个类可以协同工作。也称包装器(Wrapper),属于结构型模式,可以理解为原本不兼容的接口,通过适配修改做到统一。

    工作原理
    将一个类的接口转换成另一种接口,让原本接口不兼容的类可以兼容。从用户的角度看不到被适配者,是解耦的。用户调用适配器转化出来的目标接口方法,适配器再调用被适配者的相关接口方法,用户收到反馈结果,感觉只是和目标接口交互。

    简单来说,适配器模式就像个插头转换器,让不同标准的插头和插座可以一起使用,而插座就是原来的接口,插头是用户期望的接口。或者类比电源适配器,把原来的220V电压转换成5V电压等。

    1. //被适配的类
    2. public class Voltage220V {
    3. public int output220V() {
    4. int src = 220;
    5. System.out.println("电压=" + src);
    6. return src;
    7. }
    8. }
    9. //适配接口
    10. public interface IVoltage5V {
    11. public int output5V();
    12. }
    13. //适配器类
    14. public class VoltageAdapter extends Voltage220V implements IVoltage5V {
    15. @Override
    16. public int output5V() {
    17. // TODO Auto-generated method stub
    18. //获取220V电压
    19. int srcV = output220V();
    20. int dstV = srcV / 44 ; //转成5v
    21. return dstV;
    22. }
    23. }
    24. //调用
    25. public class Phone {
    26. public void charging(IVoltage5V iVoltage5V) {
    27. if(iVoltage5V.output5V() == 5) {
    28. System.out.println("电压是5v,可以充电");
    29. } else if (iVoltage5V.output5V() > 5) {
    30. System.out.println("电压大于5v,不可充电");
    31. }
    32. }
    33. }
    34. //测试
    35. public class Client {
    36. public static void main(String[] args) {
    37. System.out.println("===类适配器测试===");
    38. Phone phone = new Phone();
    39. phone.charging(new VoltageAdapter());
    40. }
    41. }

  • 相关阅读:
    AIR32F103(六) ADC,I2S,DMA和ADPCM实现的录音播放功能
    Java基础知识面试高频考点
    Java代码的编译过程(没写完,不要点进来)
    全国计算机四级之网络工程师知识点(一)
    MES管理系统解决方案需要具备的7个特点
    Dubbo生态之初识分布式事务
    Read Uncommitted
    离线方式安装高可用RKE2 (版本: v1.22.13+rke2r1)记录
    爬虫基础入门
    1.2 极限的性质【极限】
  • 原文地址:https://blog.csdn.net/aasd23/article/details/137109971