工厂方法模式

时间:2022-10-02 15:55:17

工厂方法模式具体类由具体的工厂产生,

工厂接口:

package FactoryMethod;

public interface Factory {
    Product Manufacture();
}

 

工厂A:

package FactoryMethod;

public class FactoryA implements Factory {
    public Product Manufacture() {
        return new ProductA();
    }
}

 

工厂B:

package FactoryMethod;

public class FactoryB implements Factory {
    public Product Manufacture() {
        return new ProductB();
    }
}

 

抽象类:

package FactoryMethod;

public interface Product {
    void Show();
}

 

具体实现类A:

package FactoryMethod;

public class ProductA implements Product {
    public void Show() {
        System.out.println("show A");
    }
}

 

具体实现类B:

package FactoryMethod;

public class ProductB implements Product {
    public void Show() {
        System.out.println("show B");
    }
}

 

测试类:

package FactoryMethod;

public class FactoryMethodTest {
    public static void main(String[] args) {
        //客户要产品A
        FactoryA mFactoryA = new FactoryA();
        mFactoryA.Manufacture().Show();

        //客户要产品B
        FactoryB mFactoryB = new FactoryB();
        mFactoryB.Manufacture().Show();
    }
}

 

测试结果:

工厂方法模式