首页 > 代码库 > 工厂模式

工厂模式

一、大致结构(其模式主要是具体的产品有对应的具体工厂)

1、抽象工厂类

2、抽象产品类

3、具体工厂类

4、具体产品类

二、代码

1、抽象工厂类

Factory.java

package com.factory;public interface Factory {        Fruit createFruit();}

2、抽象产品类

 

package com.factory;public interface Fruit {        public void grow();        }

 

3、具体产品类Apple.java与Orangle.java

 

package com.factory;public class Apple implements Fruit {    @Override    public void grow() {        System.out.println("我真在成长......");    }}

 

package com.factory;public class Orangle implements Fruit {    @Override    public void grow() {        System.out.println("grow......");    }}

4、具体工厂类AppleFactory与OrangleFactory.java

package com.factory;public class AppleFactory implements Factory {    @Override    public Fruit createFruit() {        return new Apple();    }}

package com.factory;public class OrangleFactory implements Factory {    @Override    public Fruit createFruit() {        return new Orangle();    }}

 

5、测试类Test.java

package com.factory;public class Test {        public static void main(String[] args) {        Fruit apple = new AppleFactory().createFruit();        Fruit orangle = new OrangleFactory().createFruit();                apple.grow();        orangle.grow();    }    }

 

 

工厂模式