工厂模式之-工厂方法模式
?
下面实现工厂方法模式:
前面的具体实现类不变:
?
?
?
???? 首先抽象一个animal接口:
package factory.simpleFactory;
/**
?*
?* @author Administrator
?*/
public interface Animal {
??? void eat();
}
?????
?
??? 然后创建实现了animal接口的具体实现类:
?
??? 1 Tiger 类??
package factory.simpleFactory;
/**
?*
?* @author Administrator
?*/
public class Tiger implements Animal{
??? public void eat() {
??????? System.out.println("老虎会吃");
??? }
??? public void run(){
??????? System.out.println("老虎会跑");
??? }
}
?
?
2?? haitui类:
?
package factory.simpleFactory;
/**
?*
?* @author Administrator
?*/
public class Haitun implements Animal{
??? public void eat() {
????? System.out.println("海豚会吃");
??? }
??? public void swming(){
??????? System.out.println("海豚会游泳");
??? }
}
?
?
3?? yingwu类
package factory.simpleFactory;
/**
?*
?* @author Administrator
?*/
public class Yingwu implements Animal {
??? public void eat() {
??????? System.out.println("鹦鹉会吃");
??? }
??? public void flay() {
??????? System.out.println("鹦鹉会飞");
??? }
}
?
为了使程序有更好的拓展性,我们将工厂分为一些小的子工厂。
试想一下。我们要建一座楼。我们需要钢筋,水泥。砖头。钢筋要从钢筋工厂买,水泥要从水泥工厂买,砖头要从砖头工厂买。他们都有具体的分工。我们难道要自己来制造这些吗?
?
首先一个父接口,用来生成原料。
?
package factory.simpleFactory;
/**
?*
?* @author Administrator
?*/
public interface AnimalFactory2 {
??? Animal newAnimal();
}
?
?
完了就要创建具体的子工厂,
?
1老虎工厂
?
package factory.simpleFactory;
/**
?*
?* @author Administrator
?*/
public class TigerFactory implements AnimalFactory2 {
??
??? public Animal newAnimal() {
??????? return new Tiger();
??? }
??
}
?
?
2海豚工厂
package factory.simpleFactory;
/**
?*
?* @author Administrator
?*/
public class HaitunFactory implements AnimalFactory2 {
??? public Animal newAnimal() {
??????? return new Haitun();
??? }
}
3鹦鹉工厂
?
package factory.simpleFactory;
/**
?*
?* @author Administrator
?*/
public class YingwuFactory implements AnimalFactory2 {
??? public Animal newAnimal() {
??????? return new Yingwu();
??? }
}
?
?
测试代码:
public class TestAnimal {
??? public static void main(String[] args) {
??????? AnimalFactory2 af = new TigerFactory();
??????? Animal tiger = af.newAnimal();
??????? tiger.eat();
??????? af = new HaitunFactory();
??????? Animal haitun = af.newAnimal();
??????? haitun.eat();
??????? af = new YingwuFactory();
??????? Animal yingwu = af.newAnimal();
??????? yingwu.eat();
??? }
}
这样动物没就都跑起来了。
?
如果我们现在要创建华南虎,东北虎什么的,只需要在TigerFactory中进行创建,对其他的类没有影响。大大提高了代码的可维护性。
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?