标签:设计模式 简单工厂模式 simple factory patte
简单工厂模式是由一个工厂对象来决定创建出哪一种产品类的实例(对象),就是由一个工厂类根据传入的参数来决定需要创建哪一种产品的对象或实例。
此模式主要涉及到工厂角色,抽象产品,具体产品三个角色
工厂类(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");
}
}public class FruitGardener {
public static Fruit factory(String which) {
if (which.equalsIgnoreCase("apple")) {
return new Apple();
} else {
return new StrawBerry();
}
}
}
4:核心工厂类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");
}
}
5:测试类
public class Tests {
@Test
public void testSimpleFactory() {
FruitGardener.factory("APPLE");
FruitGardener.factory("strawberry");
}
}
Apple.Apple StrawBerry.StrawBerry Process finished with exit code 0
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>8:后面会添加源代码
简单工厂模式(simple factory pattern),布布扣,bubuko.com
简单工厂模式(simple factory pattern)
标签:设计模式 简单工厂模式 simple factory patte
原文地址:http://blog.csdn.net/lzg08_08/article/details/37582757