简单工厂模式(simple factory pattern)

简单工厂模式是由一个工厂对象来决定创建出哪一种产品类的实例(对象),就是由一个工厂类根据传入的参数来决定需要创建哪一种产品的对象或实例。

此模式主要涉及到工厂角色,抽象产品,具体产品三个角色

工厂类(Creator),此模式的核心,含有与应用紧密相关的商业逻辑,

抽象产品(Product),担任需要创建产品的父类,一般由一个java接口事抽象类来实现

具体产品(Concrete Product),需要创建的产品的实例

        源代码如下:

1:抽象产品

public interface Fruit {

    void grow();

    void plant();
}

2:具体产品1

public class Apple implements Fruit {

    public Apple() {
        System.out.println("Apple.Apple");
    }

    @Override
    public void grow() {
        System.out.println("Apple.grow");
    }

    @Override
    public void plant() {
        System.out.println("Apple.plant");

    }
}

3:具体产品2

public class StrawBerry implements Fruit {

    public StrawBerry() {
        System.out.println("StrawBerry.StrawBerry");
    }

    @Override
    public void grow() {
        System.out.println("StrawBerry.grow");

    }

    @Override
    public void plant() {
        System.out.println("StrawBerry.plant");

    }
}

 

4:核心工厂类

public class FruitGardener {

    public static Fruit factory(String which) {
        if (which.equalsIgnoreCase("apple")) {
            return new Apple();
        } else {
            return new StrawBerry();
        }
    }
}


5:测试类

public class Tests {

    @Test
    public void testSimpleFactory() {
        FruitGardener.factory("APPLE");
        FruitGardener.factory("strawberry");
    }

}

 

6:测试结果为:

 

Apple.Apple
StrawBerry.StrawBerry

Process finished with exit code 0

 


7:说明,本项目是基于maven构建,测试框架是采用 JUnit

 

 

 

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

8:后面会添加源代码
 

 



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值