1.What is Factory Pattern
Factory pattern is one of the most used design patterns in Java.This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
For example, if you want to produce bicycles, motorcycles, cars in a project,you can create a factory to do it.
2.Simple implement of Factory Pattern
In factory pattern, we create object without exposing(暴露) the creation logic to the client and reference(引用) to newly created object using a common interface.
Now, we will try do create a demo to demonstrate(演示) the use of this pattern
- Create a Shape interface and concrete(具体) classes, implementing the Shape interface.
- Define a factory class ShapeFactory
- ShapePatternDemo will use ShapeFactory to get a Shape object. It will pass information to ShapeFactory to get the type of object it needs.
This is my demo’s structure, part of source code and running result: