Factory(工厂模式)与Factory Method(工厂方法模式)
程序员文章站
2022-06-15 10:16:16
...
Factory(工厂模式)与Factory Method(工厂方法模式)
工厂系列介绍
- 简单工厂
- 静态工厂
- 工厂方法
- 抽象工厂
- SpringIOC
定义
- 任何可以生产对象的方法或类,都可以称之为工厂
- 单例也是一种工厂
- 不可咬文嚼字,死扣概念
- 为什么有了new之后,还会有工厂?
- 灵活控制生产过程
- 权限、修饰、日志。。。
举例
- 任意定制交通工具
- 任意定制生产过程
- 任意定制产品一族
简单的工厂模式(可扩展性不高)
package factory;
/**
* 简单工厂的可扩展性不好
*/
public class SimpleVehicleFactory {
public Car createCar(){
return new Car();
}
public Broom createBroom(){
return new Broom();
}
}
package factory;
public class CarFactory {
public Car create(){
return new Car();
}
}
package factory;
public class Car {
public void go() {
System.out.println("a car created!");
}
}
package factory;
public class Broom {
public void go() {
System.out.println("a Broom created!");
}
}
package factory;
public class Main {
public static void main(String[] args) {
Car car = new CarFactory().create();
Broom broom = new SimpleVehicleFactory().createBroom();
car = new SimpleVehicleFactory().createCar();
car.go();
}
}
抽象工厂设计
package abstractfactory;
public abstract class AbstractFactory {
abstract Food createFood();
abstract Vehicle createVehicle();
abstract Weapon createWeapon();
}
package abstractfactory;
public class MagicFactory extends AbstractFactory {
@Override
Food createFood() {
return new MushRoom();
}
@Override
Vehicle createVehicle() {
return new Broom();
}
@Override
Weapon createWeapon() {
return new MagicStick();
}
}
package abstractfactory;
public class ModernFactory extends AbstractFactory {
@Override
Food createFood() {
return new Bread();
}
@Override
Vehicle createVehicle() {
return new Car();
}
@Override
Weapon createWeapon() {
return new AK47();
}
}
package abstractfactory;
public abstract class Food {
abstract void food();
}
package abstractfactory;
public abstract class Vehicle {
abstract void go();
}
package abstractfactory;
public abstract class Weapon {
abstract void shoot();
}
package abstractfactory;
public class AK47 extends Weapon{
@Override
public void shoot(){
System.out.println("tutututu.............");
}
}
package abstractfactory;
public class Bread extends Food{
@Override
void food() {
System.out.println("wdm");
}
}
package abstractfactory;
public class Broom extends Vehicle{
@Override
public void go() {
System.out.println("a car Broom!");
}
}
package abstractfactory;
public class Car extends Vehicle{
@Override
public void go() {
System.out.println("a car created!");
}
}
package abstractfactory;
public class MagicStick extends Weapon {
@Override
public void shoot(){
System.out.println("diandian.................");
}
}
package abstractfactory;
public class MushRoom extends Food{
@Override
public void food(){
System.out.println("dmg");
}
}
上一篇: 微信小程序开发时遇到的问题--navigator导航
下一篇: oracle存储过程简单示例