工厂模式的写法

1. 简单工厂模式

使用抽象类, 通过遍历获取实例

public abstract class Cellphone {
    public abstract void start();
}

public class CellphoneFactory {
    public static Cellphone create(String type){
        if (Objects.equals(type, "xiaomi")){
            return new Xiaomi();
        }
        if (Objects.equals(type, "iphone")){
            return new Iphone();
        }
        return null;
    }
}

public class Iphone extends Cellphone {
    @Override
    public void start() {
        System.err.println("this is iphone");
    }
}

public class Xiaomi extends Cellphone {
    @Override
    public void start() {
        System.err.println("this is xiaomi");
    }
}

2. 工厂模式

使用反射获取实例

public abstract class Cellphone {
    public abstract void start();
}

public abstract class CellphoneFactory {
    public abstract  T createCellphone(Class tClass);
}

public class LocalCellphoneFactory extends CellphoneFactory {
    @Override
    public  T createCellphone(Class tClass) {
        Cellphone cellphone = null;
        String className = tClass.getName();
        try {
            cellphone = (Cellphone) Class.forName(className).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) cellphone;
    }
}


你可能感兴趣的:(工厂模式的写法)