前面我们复习了工厂模式中的简单工厂模式与工厂方法模式,这次就来复习一下工厂模式中的最后一个成员—抽象工厂模式。
工厂方法模式中,我们是把工厂抽象出来了,而抽象工厂模式是在此基础上把产品抽象出来,结构如下图:
理论知识就不多说了,直接上代码,还是以水果为例子,现在的需求是引进了大鹏种植技术,需要在大棚里种植热带与亚热带的水果,蔬菜;
定义产品接口
分为水果和蔬菜两种
- 水果
/**
* 水果的接口
* @author Administrator
* */
public interface Fruit {
/**
* 种植
*/
void plant();
/**
* 生长
*/
void grow();
/**
* 收获
*/
void harvest();
}
- 蔬菜
/**
* 蔬菜的接口
*
* @author Administrator
*
*/
public interface Vegetables {
/**
* 种植
*/
void plant();
/**
* 生长
*/
void grow();
/**
* 收获
*/
void harvest();
}
在实际的业务中 ,这两个接口的内容按实际业务设计
定义工厂接口
这里的工厂接口是一个标识接口,也就是没有任何要实现的方法;
/**
* 标识接口
* 空实现
* @author Administrator
*
*/
public interface Creator {
}
定义具体工厂
- 热带工厂
/**
* 热带生产工厂
*
* @author Administrator
*
*/
public class TropicCreator implements Creator {
/**
* 生产热带水果
*/
public TropicFruit createTropicFruit() {
return new TropicFruit().setName("我是热带水果");
}
/**
* 生产热带蔬菜
*/
public TropicVegetables createTropicVegetables() {
return new TropicVegetables().setName("我是热带蔬菜");
}
}
- 亚热带工厂
/**
* 亚热带生产工厂
*
* @author Administrator
* */
public class SubtropicsCreator implements Creator {
/**
* 生产亚热带水果
*/
public SubtropicsFruit createSubtropicsFruit() {
return new SubtropicsFruit().setName("我是亚热带水果");
}
/**
* 生产亚热带蔬菜
*/
public SubtropicsVegetables createSubtropicsVegetables() {
return new SubtropicsVegetables().setName("我是亚热带蔬菜");
}
}
定义具体的产品
/**
* 热带水果
*
* @author Administrator
*
*/
public class TropicFruit implements Fruit {
private String name;
public String getName() {
System.out.println(name);
return name;
}
public TropicFruit setName(String name) {
this.name = name;
return this;
}
@Override
public void plant() {
// TODO Auto-generated method stub
}
@Override
public void grow() {
// TODO Auto-generated method stub
}
@Override
public void harvest() {
// TODO Auto-generated method stub
}
}
就不一一贴出代码了
测试一番:
public class Test {
public static void main(String[] args) {
TropicCreator mTropicCreator = new TropicCreator();
TropicFruit tropicFruit = mTropicCreator.createTropicFruit();
TropicVegetables tropicVegetables = mTropicCreator.createTropicVegetables();
tropicFruit.getName();
tropicVegetables.getName();
}
}
我是热带水果
我是热带蔬菜
okay 工厂模式的几种形态都复习完了!!!
下载地址:http://download.csdn.net/my