导学

工厂模式,顾名思义就是类比工厂,用于生产的意思。在Java中这样的一个工厂它生产的产品是对象。

工厂模式的特点

  1. 工厂模式用于隐藏创建对象的细节;
  2. 工厂模式核心:工厂类(Fcatory);
  3. 工厂模式可细分为简单工厂、工厂方法与抽象工厂;

工厂模式主要是通过一个“中间人”来简化对象创建的过程,这个中间人就是工厂类,工厂类可根据使用行为细分为简单工厂、工厂方法和抽象工厂,其目的都是为了隐藏创建类的细节,但设计理念有所不同。

工厂模式的实现

简单工厂模式

  1. public interface Product {
  2. public void desc();
  3. }
  4. public class MobilePhone implements Product {
  5. @Override
  6. public void desc() {
  7. System.out.println("生产手机");
  8. }
  9. }
  10. public class Pad implements Product {
  11. @Override
  12. public void desc() {
  13. System.out.println("生产平板");
  14. }
  15. }
  16. public class Computer implements Product {
  17. @Override
  18. public void desc() {
  19. System.out.println("生产电脑");
  20. }
  21. }
  22. public class Factory {
  23. public static Product produce(String pName) {
  24. if("phone".equals(pName)) {
  25. return new MobilePhone();
  26. } else if("computer".equals(pName)) {
  27. return new Computer();
  28. } else if("pad".equals(pName)) {
  29. return new Pad();
  30. } else {
  31. return null;
  32. }
  33. }
  34. }
  35. public class Demo {
  36. public static void main(String[] args) {
  37. Product pdt = Factory.produce("pad");
  38. pdt.desc();
  39. }
  40. }

工厂模式
工厂方法模式,是对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象

  1. public interface Product {
  2. public void desc();
  3. }
  4. public class MobilePhone implements Product {
  5. @Override
  6. public void desc() {
  7. System.out.println("生产手机");
  8. }
  9. }
  10. public class Pad implements Product {
  11. @Override
  12. public void desc() {
  13. System.out.println("生产平板");
  14. }
  15. }
  16. public class Computer implements Product {
  17. @Override
  18. public void desc() {
  19. System.out.println("生产电脑");
  20. }
  21. }
  22. public class Factory {
  23. //手机生产线
  24. public static Product mobilePhone() {
  25. return new MobilePhone();
  26. }
  27. //电脑生产线
  28. public static Product computer() {
  29. return new Computer();
  30. }
  31. //平板生产线
  32. public static Product pad() {
  33. return new Pad();
  34. }
  35. }
  36. public class Demo {
  37. public static void main(String[] args) {
  38. Product pdt = Factory.computer();
  39. pdt.desc();
  40. }
  41. }

抽象工厂模式
自学完成