工厂方法模式
鼠标工厂是个父类,有生产鼠标这个接口。
戴尔鼠标工厂、惠普鼠标工厂 分别继承它,可以分别生产戴尔鼠标,惠普鼠标。
生产哪种鼠标不再由参数决定,而是创建鼠标工厂时,由戴尔鼠标工厂或者惠普鼠标工厂创建。
后续直接调用鼠标工厂.生产鼠标()即可。
实现:
- mouse基础类
/**
* 鼠标抽象类
*
* @author liuyuan
* @version BaseMouse.java, v 0.1 2020-04-12 11:21
*/
public abstract class BaseMouse {
/**
* 生产鼠标的抽象方法
*/
public abstract void sayHi();
}
/**
* 戴尔实现类
*
* @author liuyuan
* @version DellMouse.java, v 0.1 2020-04-12 11:23
*/
public class DellMouse extends BaseMouse {
@Override
public void sayHi() {
System.out.println("dell 生产鼠标~");
}
}
/**
* 惠普实现类
*
* @author liuyuan
* @version HpMouse.java, v 0.1 2020-04-12 11:23
*/
public class HpMouse extends BaseMouse {
@Override
public void sayHi() {
System.out.println("HP 生产鼠标~");
}
}
- factory工厂类
import com.example.designmode.factory.factorymethod.mouse.BaseMouse;
/**
* 鼠标工厂抽象类
*
* @author liuyuan
* @version BaseMouseFactory .java, v 0.1 2020-04-12 11:25
*/
public abstract class BaseMouseFactory {
public abstract BaseMouse greatMouse();
}
import com.example.designmode.factory.factorymethod.mouse.BaseMouse;
import com.example.designmode.factory.factorymethod.mouse.DellMouse;
/**
* 戴尔鼠标工厂实现类
*
* @author liuyuan
* @version DellMouseFactory.java, v 0.1 2020-04-12 11:36
*/
public class DellMouseFactory extends BaseMouseFactory {
@Override
public BaseMouse greatMouse() {
return new DellMouse();
}
}
import com.example.designmode.factory.factorymethod.mouse.BaseMouse;
import com.example.designmode.factory.factorymethod.mouse.HpMouse;
/**
* 惠普鼠标工厂实现类
*
* @author liuyuan
* @version HpMouseFactory.java, v 0.1 2020-04-12 11:36
*/
public class HpMouseFactory extends BaseMouseFactory {
@Override
public BaseMouse greatMouse() {
return new HpMouse();
}
}
- 测试
/**
* fshows.com
* Copyright (C) 2013-2020 All Rights Reserved.
*/
package com.example.designmode.factory.factorymethod;
import com.example.designmode.factory.factorymethod.factory.BaseMouseFactory;
import com.example.designmode.factory.factorymethod.factory.DellMouseFactory;
import com.example.designmode.factory.factorymethod.factory.HpMouseFactory;
/**
* 工厂方法模式
*
* @author liuyuan
* @version Test.java, v 0.1 2020-04-11 19:19
*/
public class Test {
public static void main(String[] args) {
System.out.println("~~~工厂方法模式~~~");
BaseMouseFactory mouseFactory = new DellMouseFactory();
// dell 生产鼠标~
mouseFactory.greatMouse().sayHi();
mouseFactory = new HpMouseFactory();
// HP 生产鼠标~
mouseFactory.greatMouse().sayHi();
}
}