工厂模式是java中最常用的设计模式之一。 这种类型的设计模式属于创建模式,因为此模式提供了创建对象的最佳方法之一。
在工厂模式中,我们没有创建逻辑暴露给客户端创建对象,并使用一个通用的接口引用新创建的对象。 (推荐学习:java课程)
实现方法
我们将创建一个shape接口和实现shape接口的具体类。 一个工厂类shapefactory会在下一步中定义。
factorypatterndemo这是一个演示类,将使用shapefactory来获取一个shape对象。它会将信息(circle/rectangle/square)传递给shapefactory以获取所需的对象类型。
实现工厂模式的结构如下图所示 -
第1步
创建一个接口-
shape.javapublic interface shape { void draw();}
第2步
创建实现相同接口的具体类。如下所示几个类 -
rectangle.javapublic class rectangle implements shape { @override public void draw() { system.out.println("inside rectangle::draw() method."); }}square.javapublic class square implements shape { @override public void draw() { system.out.println("inside square::draw() method."); }}circle.javapublic class circle implements shape { @override public void draw() { system.out.println("inside circle::draw() method."); }}
第3步
创建工厂根据给定的信息生成具体类的对象。
shapefactory.javapublic class shapefactory { //use getshape method to get object of type shape public shape getshape(string shapetype){ if(shapetype == null){ return null; } if(shapetype.equalsignorecase("circle")){ return new circle(); } else if(shapetype.equalsignorecase("rectangle")){ return new rectangle(); } else if(shapetype.equalsignorecase("square")){ return new square(); } return null; }}
第4步
使用工厂通过传递类型等信息来获取具体类的对象。
factorypatterndemo.javapublic class factorypatterndemo { public static void main(string[] args) { shapefactory shapefactory = new shapefactory(); //get an object of circle and call its draw method. shape shape1 = shapefactory.getshape("circle"); //call draw method of circle shape1.draw(); //get an object of rectangle and call its draw method. shape shape2 = shapefactory.getshape("rectangle"); //call draw method of rectangle shape2.draw(); //get an object of square and call its draw method. shape shape3 = shapefactory.getshape("square"); //call draw method of circle shape3.draw(); }}
第5步
验证输出结果如下-
inside circle::draw() method.inside rectangle::draw() method.inside square::draw() method.
以上就是java工厂设计模式课程详解的详细内容。