java 工厂模式简单介绍及例子
java中工厂模式在java ee中经常碰见,是一种常见的模式,其可分为三种:静态工厂模式、工厂方法模式、抽象工厂模式。一下做一简单讲述和例子。
?
静态工厂模式:顾名思义就知道他是用静态方法实现的,其创建的对象具有一定的特性,譬如说是某类的派生或者某接口的实现。其比较简单。例子如下
?
Animal类:
?
package com.test;import org.junit.Test;import com.bean.Animal;import com.bean.Cat;import com.bean.Dog;import com.factory.AnimalMother;import com.factory.MilkAnimalMother;import com.factory.impl.CatMother;import com.factory.impl.CattleMilkMother;import com.factory.impl.DogMother;import com.factory.impl.SheepMilkMother;import com.factory.sta.StaticFatory;/** * 测试类 * * @author Lyon Yao * */public class TestCase {/** * 静态工厂类 测试 */@Testpublic void staticFactoryTest() {Animal ani1=(Animal) StaticFatory.getInstance(Cat.class.getName());System.out.println(ani1.getName());ani1.eat();ani1=(Animal) StaticFatory.getInstance(Dog.class.getName(),"dog");System.out.println(ani1.getName());ani1.eat();}/** * 工厂方法模式测试 */@Testpublic void methodFactoryTest(){AnimalMother mother=new CatMother();mother.giveBirth();mother=new DogMother();mother.giveBirth();}/** * 抽象工厂模式测试 */@Testpublic void abstrFactoryTest(){MilkAnimalMother mother=new SheepMilkMother();mother.giveBirth();mother.produceMilk();mother=new CattleMilkMother();mother.giveBirth();mother.produceMilk();}}?控制台输出:
?
?
null
I like to eat fish!
dog
I like to eat bone!
猫母亲生了一只小猫眯
狗母亲生了一只小狗
奶羊生了一只小羊
奶羊生产了羊奶
奶牛生了一只小牛
奶牛生产了牛奶
?
?
例子可能比较牵强,各位见笑了。