工厂方法模式
工厂方法模式是一种创建型设计模式,在父类中提供一个创建对象的方法,允许子类决定实例化对象的类型
例如我们有一份运输苹果的业务,运营的很好,第二天业务扩展,我们又要运输鸭梨,这时候如果不使用工厂方法就会有代码侵入去增加运输鸭梨的业务场景,如果后来又有火龙果、葡萄、草莓呢?或者鸭梨不运输了呢?都存在代码侵入的情况;
由此使用工厂方法,创建通用父类并提供创建对象的方法,允许子类决定实例化对象的类型,以此降低代码的侵入;
public interface Fruit {
//抽象出行为
void action();
}
public interface FuitsInterfaceFactory {
//生产抽象行为类
Fruit createFruit();
}
public class Apple implements Fruit{
@Override
public void action() {
System.out.println("运输苹果");
}
}
public class Blanana implements Fruit{
@Override
public void action() {
System.out.println("运输香蕉");
}
}
public class AppleFactory implements FuitsInterfaceFactory{
@Override
public Fruit createFruit() {
return new Apple();
}
}
public class BananaFactory implements FuitsInterfaceFactory{
@Override
public Fruit createFruit() {
return new Blanana();
}
}
public class Test {
public static void main(String[] args) {
Fruit fruit = new AppleFactory().createFruit();
fruit.action();
Fruit fruit1 = new BananaFactory().createFruit();
fruit1.action();
/**
* 输出
* 运输苹果
* 运输香蕉
*/
}
}
抽象工厂模式
public interface Shape {
//绘制
void draw();
}
public class Square implements Shape{
@Override
public void draw() {
System.out.println("绘制正方图形");
}
}
public class Round implements Shape{
@Override
public void draw() {
System.out.println("绘制圆形");
}
}
public interface Color {
//填充颜色
void fill();
}
public class Blue implements Color{
@Override
public void fill() {
System.out.println("填充蓝色");
}
}
public class Red implements Color{
@Override
public void fill() {
System.out.println("填充红色");
}
}
抽象工厂抽象出行为
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape);
}
public class ColorFactory extends AbstractFactory{
@Override
Color getColor(String color) {
if (color.equals("red")) {
return new Red();
}
return new Blue();
}
@Override
Shape getShape(String shape) {
return null;
}
}
public class ShapeFactory extends AbstractFactory{
@Override
Color getColor(String color) {
return null;
}
@Override
Shape getShape(String shape) {
if (shape.equals("round")) {
return new Round();
}
return new Square();
}
}
工厂生成器
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
} else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}
测试
public class Main {
public static void main(String[] args) {
AbstractFactory color = FactoryProducer.getFactory("Color");
Color red = color.getColor("red");
red.fill();
AbstractFactory shape = FactoryProducer.getFactory("SHAPE");
Shape round = shape.getShape("round");
round.draw();
}
}
填充红色
绘制圆形