天天看點

圖圖談設計模式——靜态工廠設計模式_java

建立時間: 2016/11/9 8:37
作者: [email protected]

圖圖接下來将介紹第二種設計模式,工廠設計模式。工廠,見名知意,就是建立産品的。

同樣在java中,是用來建立對象的。為什麼用工廠模式呢,因為他可以解耦,可擴充。友善開發。

而最常用的就是靜态工廠模式,(很多時候會結合單例模式,new出來的對象是單例的)

簡單的UML圖(有瑕疵)如下

圖圖談設計模式——靜态工廠設計模式_java
package org.huey.partten.factory.factorymethod;
/**
 * 抽象産品
 * @author huey
 *
 */
public interface Computer {
     public void run();
}
package org.huey.partten.factory.factorymethod;
/*
 * 工廠接口
 * @author huey
 *
 */
public interface ComputerFactory {
     public Computer createComputer();
}
package org.huey.partten.factory.factorymethod;
/**
 * 詳細産品
 * @author huey
 *
 */
public class Dell implements Computer{
     @Override
     public void run() {
          System.out.println(Dell.class.getSimpleName()+"跑起來了!");
     }
}
package org.huey.partten.factory.factorymethod;
public class DellFactory implements ComputerFactory {
     @Override
     public Computer createComputer() {
          return new Dell();
     }
}
package org.huey.partten.factory.factorymethod;
public class Lenovo implements Computer{
     @Override
     public void run() {
          System.out.println(this.getClass().getSimpleName()+"跑起來了!");
     }
}
package org.huey.partten.factory.factorymethod;
public class LenovoFactory implements ComputerFactory{
     @Override
     public Computer createComputer() {
          return new Lenovo();
     }
}
package org.huey.partten.factory.factorymethod;
/**
 * 測試
 * @author huey
 *
 */
public class FactoryMethodFactoryTest {
     public static void main(String[] args) {
          ComputerFactory dellFactory = new DellFactory();
          Computer dell = dellFactory.createComputer();
          dell.run();
          ComputerFactory lenovoFactory = new LenovoFactory();
          Computer lenovo = lenovoFactory.createComputer();
          lenovo.run();
     }
}
測試           

複制

圖圖談設計模式——靜态工廠設計模式_java