设计模式-0-简单工厂模式

  简单工厂模式不属于23中设计模式当中,简单工厂模式一般分为普通简单工厂模式、多方法简单工厂、静态简单工厂。
  01、普通简单工厂模式
  普通简单工厂模式的理解是:一个接口中包含一个方法a,由两个不同的class(B和C)来实现,再新建一个class D(所谓的工厂),D中创建一方法e,其他使用者通过调用e来实例化B或C(通过传入不同的code值来判断是创建B还是C)
  例:
  接口中方法a:send
	public interface testInterface {
	    public void send();
	}
	B:test2实现方法a:
	public class test2 implements testInterface {
	    public void send() {
	        System.out.println("this is test2");
	    }
	}
	C:test3实现方法a:
	public class test3 implements testInterface{
	    public void send(){
	        System.out.println("this is test3");
	    }
	}
	创建工厂D:FactoryTest 
	工厂中实例B和C方法e:produce
	public class FactoryTest {
	    public testInterface produce(String type){
	        if("test2".equals(type)){
	            return  new test2();
	        }else if("test3".equals(type)){
	            return  new test3();
	        }else {
	            System.out.println("请输入正确的类型!");
	            return null;
	        }
	    }
	}
	第三方调用测试:
	public class test {
	    @Test
	    public void testH() {
	        FactoryTest factoryTest = new FactoryTest();
	        //实例化test3
	        testInterface test = factoryTest.produce("test3");
	        test.send();
	        //实例化test2
	        testInterface testf = factoryTest.produce("test2");
	        testf.send();
	    }
	}
	缺点:如果传入的字符串有误,不能正确创建对象
	
	02 多方法简单工厂
	多方法简单工厂与简单工厂类似,不同点在于工厂D实例B和C时不再使用同一个方法e,而是针对B和C采用不用的实例方法(设为d和f),即调用不同的方法实列化a的不同实现类。
	例:
	a、B和C与简单工厂一样,不再贴出
	工厂class D:FactoryTest
	实例化B的方法d:produce2
	实例化C的方法f:produce3
	public class FactoryTest {
	    public testInterface produce2(){
	            return  new test2();
	    }
	    public testInterface produce3(){
	            return  new test3();
	    }
	}
	第三方调用案例:
	public class test {
	    @Test
	    public void testH() {
	        FactoryTest factoryTest = new FactoryTest();
	        //实例化test3
	        testInterface test = factoryTest.produce3();
	        test.send();
	        //实例化test2
	        testInterface testf = factoryTest.produce2();
	        testf.send();
	    }
	}

03 多静态简单工厂方法
将多简单工厂方法中工厂D的实例方法换成静态函数,在使用过程中不用实例化工厂。
例如:
a、B和C与简单工厂一样,不再贴出
工厂class D:FactoryTest
实例化B的方法d:produce2
实例化C的方法f:produce3
public class FactoryTest {
public static testInterface produce2(){
return new test2();
}
public static testInterface produce3(){
return new test3();
}
}
第三方调用案例:不用再对工厂进行实例化
public class testmain {
public static void main(String[] args){
testInterface test=FactoryTest.produce3();
//运行test3的send方法
test.send();
testInterface testf=FactoryTest.produce2();
//运行test2的send方法
testf.send();
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值