工厂模式大体可以分为三种:简单工厂模式、抽象工厂模式、工厂方法模式
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");
这个就是简单工厂的大体逻辑。
下面接着我们说工厂方法:
定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
类图:
工厂方法模式代码
- interface IProduct {
- public void productMethod();
- }
- class Product implements IProduct {
- public void productMethod() {
- System.out.println("产品");
- }
- }
- interface IFactory {
- public IProduct createProduct();
- }
- class Factory implements IFactory {
- public IProduct createProduct() {
- return new Product();
- }
- }
- public class Client {
- public static void main(String[] args) {
- IFactory factory = new Factory();
- IProduct prodect = factory.createProduct();
- prodect.productMethod();
- }
- }
典型应用就是组装汽车,实例化各个组件类,然后拼装在一起就形成产品了
- interface IFactory {
- public ICar createCar();
- }
- class Factory implements IFactory {
- public ICar createCar() {
- Engine engine = new Engine();
- Underpan underpan = new Underpan();
- Wheel wheel = new Wheel();
- ICar car = new Car(underpan, wheel, engine);
- return car;
- }
- }
- public class Client {
- public static void main(String[] args) {
- IFactory factory = new Factory();
- ICar car = factory.createCar();
- car.show();
- }
- }
放大