作者:最傻的傻瓜z1998 | 来源:互联网 | 2023-10-17 17:00
一篇博客读懂设计模式之—工厂模式 工厂模式在我们日常开发的时候经常用到,相信大家都有了一定的了解,工厂模式是一种创建对象的设计模式,它提供一种创建对象的最佳方式。
主要过程是: 定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
工厂模式主要有常见的三种类型:简单工厂模式,工厂方法模式,抽象工厂模式。下面我们分别用代码来介绍一下这三种模式的演化过程:
简单工厂模式
添加一个接口 public interface Car { String getBrand ( ) ; }
添加几个实现类实现接口 public class Bmw implements Car { @Override public String getBrand ( ) { return "BMW" ; } }
public class Benz implements Car { @Override public String getBrand ( ) { return "Benz" ; } }
public class Audi implements Car { @Override public String getBrand ( ) { return "Audi" ; } }
添加一个方法来选择创建的对象 public class SimpleFactory { public Car getCar ( String name) { if ( "BMW" . equalsIgnoreCase ( name) ) { return new Bmw ( ) ; } else if ( "Benz" . equalsIgnoreCase ( name) ) { return new Benz ( ) ; } else if ( "audi" . equalsIgnoreCase ( name) ) { return new Audi ( ) ; } else { return null; } } }
添加测试类: public class TestSimpleFactory { public static void main ( String[ ] args) { SimpleFactory simpleFactory = new SimpleFactory ( ) ; Car car = simpleFactory. getCar ( "" ) ; System. out. println ( car. getBrand ( ) ) ; } }
工厂方法模式:
添加一个工厂的接口 public interface Factory { Car getCar ( ) ; }
实现接口的工厂类 public class AudiFactory implements Factory { @Override public Car getCar ( ) { return new Audi ( ) ; } }
public class BenzFactory implements Factory { @Override public Car getCar ( ) { return new Benz ( ) ; } }
public class BmwFactory implements Factory { @Override public Car getCar ( ) { return new Bmw ( ) ; } }
测试类: public class TestFuncFactory { public static void main ( String[ ] args) { System. out. println ( new BenzFactory ( ) . getCar ( ) ) ; System. out. println ( new BmwFactory ( ) . getCar ( ) ) ; System. out. println ( new AudiFactory ( ) . getCar ( ) ) ; } }
抽象工厂方法: 整合了前面两种模式
添加一个抽象工厂 public abstract class AbstractFactory { abstract Car getCar ( ) ; public Car getCar ( String name) { if ( "BMW" . equalsIgnoreCase ( name) ) { return new BmwFactory ( ) . getCar ( ) ; } else if ( "Benz" . equalsIgnoreCase ( name) ) { return new BenzFactory ( ) . getCar ( ) ; } else if ( "audi" . equalsIgnoreCase ( name) ) { return new AudiFactory ( ) . getCar ( ) ; } else { return null; } } }
添加一个默认实现类 public class DefaultFactory extends AbstractFactory { @Override Car getCar ( ) { return new BenzFactory ( ) . getCar ( ) ; } }
测试类 public class TestAbstrFactory { public static void main ( String[ ] args) { DefaultFactory defaultFactory = new DefaultFactory ( ) ; System. out. println ( defaultFactory. getCar ( "bmw" ) ) ; } }
**
后期会继续完善 欢迎留言点赞!! **