【设计模式】工厂模式

来源:互联网 发布:ip地址转网络字节序 编辑:程序博客网 时间:2024/05/24 06:47

工厂模式大体可以分为三种:简单工厂模式、抽象工厂模式、工厂方法模式

1.先来说下简单工厂模式:所谓简单工厂,故名思意,简单,怎么个简单,就是给一个名称创建一个对象。

简单工厂模式有几个对象:

工厂实体:本模式的核心类(用来创建东西的类,当然核心)

抽象产品:一般具有共同特性的父类(比如:汽车的接口类)

具体的产品:继承抽象产品的父类(比如:BMW继承汽车接口类,奔驰继承汽车接口类)

简单工厂怎么使用呢?


抽象产品:

public interface Car{   public void drive(); }

具体的产品实现:

BWM继承父类

public class Bmw implements Car{public void drive()  {System.out.println("Driving Bmw ");}}
奔驰

public class Benz implements Car{public void drive()  {System.out.println("Driving Benz ");}}

工厂类的实现:

public class Factory{//工厂方法.注意 返回类型为抽象产品角色       public static Car driverCar(String s)throws Exception    {              //判断逻辑,返回具体的产品角色给Client              if(s.equalsIgnoreCase("Benz"))                       return new Benz();              else if(s.equalsIgnoreCase("Bmw"))                     return new Bmw();}}


一个土豪客户说要生产5W辆BWM,

Car bwmCar = Factory.driverCar("Bmw");
这个就是简单工厂的大体逻辑。


下面接着我们说工厂方法:

定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。

类图:

工厂方法模式代码

[java] view plaincopy
  1. interface IProduct {  
  2.     public void productMethod();  
  3. }  
  4.   
  5. class Product implements IProduct {  
  6.     public void productMethod() {  
  7.         System.out.println("产品");  
  8.     }  
  9. }  
  10.   
  11. interface IFactory {  
  12.     public IProduct createProduct();  
  13. }  
  14.   
  15. class Factory implements IFactory {  
  16.     public IProduct createProduct() {  
  17.         return new Product();  
  18.     }  
  19. }  
  20.   
  21. public class Client {  
  22.     public static void main(String[] args) {  
  23.         IFactory factory = new Factory();  
  24.         IProduct prodect = factory.createProduct();  
  25.         prodect.productMethod();  
  26.     }  

典型应用就是组装汽车,实例化各个组件类,然后拼装在一起就形成产品了

  1. interface IFactory {  
  2.     public ICar createCar();  
  3. }  
  4. class Factory implements IFactory {  
  5.     public ICar createCar() {  
  6.         Engine engine = new Engine();  
  7.         Underpan underpan = new Underpan();  
  8.         Wheel wheel = new Wheel();  
  9.         ICar car = new Car(underpan, wheel, engine);  
  10.         return car;  
  11.     }  
  12. }  
  13. public class Client {  
  14.     public static void main(String[] args) {  
  15.         IFactory factory = new Factory();  
  16.         ICar car = factory.createCar();  
  17.         car.show();  
  18.     }  
  19. }  


放大





原创粉丝点击