首页 > 学院 > 开发设计 > 正文

设计模式之 工厂模式(Factory)

2019-11-11 05:00:31
字体:
来源:转载
供稿:网友

1.工厂模式的作用

工厂模式封装了对象创建的过程,低程序模块之间的耦合度。

2.工厂模式一般有哪几种

1.普通工厂2.工厂方法3.抽象工厂

3.示例代码:

1.所需要的接口和实现类public interface Animal{//定义一个接口,之后需要的实体类都将实现该接口 public abstract void eat();}public class Person implements Animal{ public void eat(){ System.out.PRintln("我是佩森"); }}public class Dog implements Animal{ public void eat(){ System.out.println("我是道格"); }}public class Cat implements Animal{ public void eat(){ System.out.println("我是凯特"); }}2.普通工厂类public class AnimalFactory{//动物工厂类 public Animal getAnimal(String typeName) throws Exception{ if("Person".equals(typeName)) return new Person(); else if("Dog".equals(typeName)) return new Dog(); else if("Cat".equals(typeName)) return new Cat(); else throw new Exception("TypeName error"); }}//调用:public void test(){ AnimalFactory af = new AnimalFactory(); try { Dog dog = (Dog) af.getAnimal("Dog"); dog.eat(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }}//输出:我是道格//以上代码可以把getAnimal()设置为静态方法,方便调用//上面的代码是普通工厂模式,但是有个缺点,假如这个工厂能创建100个不同的实体类,那么逻辑控制就显得十分繁杂,下面的代码是反射版本的,解决了以上问题public Animal getAnimal(String className) throws Exception { return (Animal) Class.forName(className).newInstance();}//注意:调用的时候className为该类的全限定名2.工厂方法public Animal AnimalFactroyMethod{ public Animal getDog(){ return new Dog(); } public Animal getCat(){ return new Cat(); } public Animal getPerson(){ return new Person(); }}//调用方式就是调用类中的方法获得相应实体类对象,这样避免了由于传入参数的错误导致报错//但是问题又来了,假如我有开始有1个,然而后来我又需要一个方法来提供对象,这样我们只能修改原来的类,这样就违背了开闭原则3.抽象工厂方法//为了解决以上问题,我们可以将工厂类抽象出来,每当需要新的类型时候,就创建一个实现该接口的工厂类,代码如下://抽象工厂public interface PublicFactory{ public Animal produce();}//Dog类的工厂public class DogFactory implements PublicFactory{ public Animal produce(){ return new Dog(); }}//其他动物都是这样的,现在我们要添加一个新动物public class Snake implements Animal{ public void eat(){ System.out.println("蛇吃东西"); }}//蛇的工厂类public class SnakeFactory implements PublicFactory{ public Animal produce(){ return new Snake(); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表