简单工厂模式:定一个工厂类,可以根据不同的参数,返回不同的类的实例,这些类通常有共同的父类

    优点:
    高内聚,松耦合。使用工厂类时,只需要传入正确的参数,就可以获取需要的对象,无需知道其实现过程。

    实现:
    业务场景:例如我需要创建一个咖啡店,当客户需要某种咖啡并且店内可以提供的时候,我就为其提供一杯咖啡。这时候,这家咖啡店就可以当作一个咖啡工厂,生产出来的咖啡可以被当作产品,咖啡名称可以当作参数。工厂可以根据不同的参数,返回不同的产品,这就是简单工厂模式。

    1、咖啡类(产品)

    1. /**
    2. * 咖啡类(父类)
    3. */
    4. public abstract class Coffee {
    5. /**
    6. * 制作咖啡
    7. */
    8. public abstract void makeCoffee();
    9. }
    10. /**
    11. * 蓝山咖啡
    12. */
    13. public class CoffeeLanshan extends Coffee{
    14. public void makeCoffee(){
    15. System.out.println("制作了一杯蓝山咖啡");
    16. }
    17. }
    18. /**
    19. * 猫屎咖啡
    20. */
    21. public class CoffeeMaoShi extends Coffee{
    22. public void makeCoffee(){
    23. System.out.println("制作了一杯猫屎咖啡");
    24. }
    25. }

    2、咖啡工厂类

    1. /**
    2. * 咖啡工厂类
    3. */
    4. public class CoffeeFactory {
    5. public static Coffee getCoffee(String name){
    6. Coffee coffee = null;
    7. switch (name){
    8. case "蓝山咖啡":
    9. coffee = new CoffeeLanshan();
    10. break;
    11. case "猫屎咖啡":
    12. coffee = new CoffeeMaoShi();
    13. break;
    14. default:
    15. System.out.println("抱歉,店内没有该咖啡");
    16. break;
    17. }
    18. if (coffee != null){
    19. coffee.makeCoffee();
    20. }
    21. return coffee;
    22. }
    23. }

    3、测试

    1. /**
    2. * 简单工厂测试类
    3. */
    4. public class TestSimpleFactory {
    5. public static void main(String [] args){
    6. Coffee coffeeLanshan = CoffeeFactory.getCoffee("蓝山咖啡");
    7. Coffee coffeeMaoshi = CoffeeFactory.getCoffee("猫屎咖啡");
    8. Coffee coffeeWuming = CoffeeFactory.getCoffee("无名咖啡");
    9. }
    10. }

    测试结果:
    image.png

    同时,可优化工厂类,添加一个菜单,用户直接从菜单选择

    1. /**
    2. * 咖啡工厂类
    3. */
    4. public class CoffeeFactory {
    5. /**
    6. * 菜单
    7. */
    8. public static final class menu {
    9. public static final String LAN_SHAN = "蓝山咖啡";
    10. public static final String MAO_SHI = "猫屎咖啡";
    11. }
    12. public static Coffee getCoffee(String name){
    13. Coffee coffee = null;
    14. switch (name){
    15. case menu.LAN_SHAN:
    16. coffee = new CoffeeLanshan();
    17. break;
    18. case menu.MAO_SHI:
    19. coffee = new CoffeeMaoShi();
    20. break;
    21. default:
    22. System.out.println("抱歉,店内没有该咖啡");
    23. break;
    24. }
    25. if (coffee != null){
    26. coffee.makeCoffee();
    27. }
    28. return coffee;
    29. }
    30. }
    31. /**
    32. * 简单工厂测试类
    33. */
    34. public class TestSimpleFactory {
    35. public static void main(String [] args){
    36. Coffee coffeeLanshan = CoffeeFactory.getCoffee(CoffeeFactory.menu.LAN_SHAN);
    37. Coffee coffeeMaoshi = CoffeeFactory.getCoffee(CoffeeFactory.menu.MAO_SHI);
    38. Coffee coffeeWuming = CoffeeFactory.getCoffee("无名咖啡");
    39. }
    40. }