工厂模式学习笔记

工厂模式
定义:定义一个用于创建对象的接口,让子类决定实例化哪个类
使用场景:负责对象适合使用工厂模式,用new就可以完成创建的对象无需使用工厂模式

public abstract class Product {
    public abstract void System();
}
public class ProductA extends Product{
    private static final String TAG = "ProductA";
    @Override
    public void System() {
        Log.d(TAG, "I am A");
    }
}
public class ProductB extends Product{
    private static final String TAG = "ProductB";
    @Override
    public void System() {
        Log.d(TAG, "I am B");
    }
}

public abstract class Factory {
    public abstract Product createFactory();
}
public class FactoryA extends Factory{
    @Override
    public Product createFactory() {
        return new ProductB();
    }
}

使用:

private void useFactory(){
    Factory factory = new FactoryA();
    Product product = factory.createFactory();
    product.System();

有时候可以通过反射的方式更简洁地来生产具体产品对象

public abstract class Factory {
    public abstract  T createFactory(Class cla);
}

public class FactoryA extends Factory{

    @Override
    public  T createFactory(Class cla) {
        Product product = null;
        try {
            product = (Product)Class.forName(cla.getName()).newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return (T)product;
    }
}

使用:

Factory factory = new FactoryA();
Product product = factory.createFactory(ProductA.class);
product.System();

Android源码中的工厂模式实现
onCreate方法就相当于一个工厂方法

你可能感兴趣的:(学习,android,java)