Home  >  Article  >  Java  >  How to write code for Java factory design pattern

How to write code for Java factory design pattern

王林
王林forward
2023-05-02 19:52:121257browse

Implementation

We will create a Shape interface and concrete classes that implement the Shape interface. A factory class ShapeFactory will be defined in the next step.

FactoryPatternDemo This is a demonstration class that will use ShapeFactory to obtain a Shape object. It will pass the information (CIRCLE/RECTANGLE/SQUARE) to the ShapeFactory to get the required object type.

The structure of implementing the factory pattern is shown in the figure below-

java-61.jpg

step 1

​Create an interface-

Shape.java

publicinterfaceShape{

voiddraw();

}

Step 2

Create a concrete class that implements the same interface. Several categories are shown below-

Rectangle.java

​publicclassRectangleimplementsShape{

@Override

publicvoiddraw(){

System.out.println("InsideRectangle::draw()method.");

}

}

Square.java

​publicclassSquareimplementsShape{

@Override

publicvoiddraw(){

System.out.println("InsideSquare::draw()method.");

}

}

​Circle.java

​publicclassCircleimplementsShape{

@Override

publicvoiddraw(){

System.out.println("InsideCircle::draw()method.");

}

}

Step 3

Create a factory to generate objects of specific classes based on given information.

ShapeFactory.java

​publicclassShapeFactory{

//usegetShapemethodtogetobjectoftypeshape

publicShapegetShape(StringshapeType){

​if(shapeType==null){

returnnull;

}

​if(shapeType.equalsIgnoreCase("CIRCLE")){

returnnewCircle();

}elseif(shapeType.equalsIgnoreCase("RECTANGLE")){

returnnewRectangle();

}elseif(shapeType.equalsIgnoreCase("SQUARE")){

returnnewSquare();

}

returnnull;

}

}

Step 4

Use a factory to obtain an object of a specific class by passing information such as type.

FactoryPatternDemo.java

​publicclassFactoryPatternDemo{

publicstaticvoidmain(String[]args){

ShapeFactoryshapeFactory=newShapeFactory();

//getanobjectofCircleandcallitsdrawmethod.

Shapeshape1=shapeFactory.getShape("CIRCLE");

​ //calldrawmethodofCircle

shape1.draw();

//getanobjectofRectangleandcallitsdrawmethod.

Shapeshape2=shapeFactory.getShape("RECTANGLE");

​ //calldrawmethodofRectangle

shape2.draw();

//getanobjectofSquareandcallitsdrawmethod.

Shapeshape3=shapeFactory.getShape("SQUARE");

//calldrawmethodofcircle

shape3.draw();

}

}

Step 5

The verification output results are as follows-

​InsideCircle::draw()method.

​InsideRectangle::draw()method.

​InsideSquare::draw()method.

How to write code for Java factory design pattern

The above is the detailed content of How to write code for Java factory design pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete