工场形式是Java中最经常运用的设想形式之一。 这类范例的设想形式属于建立形式,因为此形式供应了建立对象的最好要领之一。
在工场形式中,我们没有建立逻辑暴露给客户端建立对象,并运用一个通用的接口援用新建立的对象。 (引荐进修:java课程)
完成要领
我们将建立一个Shape接口和完成Shape接口的细致类。 一个工场类ShapeFactory会在下一步中定义。
FactoryPatternDemo这是一个演示类,将运用ShapeFactory来猎取一个Shape对象。它会将信息(CIRCLE/RECTANGLE/SQUARE)通报给ShapeFactory以猎取所需的对象范例。
完成工场形式的构造以下图所示 -
第1步
建立一个接口-
Shape.java public interface Shape { void draw(); }
第2步
建立完成雷同接口的细致类。以下所示几个类 -
Rectangle.java public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } Square.java public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } Circle.java public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
第3步
建立工场依据给定的信息生成细致类的对象。
ShapeFactory.java public 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.java public 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工场设想形式课程详解的细致内容,更多请关注ki4网别的相干文章!