设计模式之工厂模式(笔记)
工厂模式式java中最常用的设计模式之一,这种类型的设计模式属于创建型模式,他提供了一种提供创建对象的最佳方式
在工厂模式种,我们创建对象时不会暴露创建逻辑,而是通过使用一个共同的接口来指向新创建的对象。
介绍
意图:
定义一个创建对象的接口,让其子类决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
主要解决了接口选择的问题,让其子类实现工厂接口。
由于java里边所有类都继承于Object类,所以,可以采用更加简单的方式实现,并且可以借助反射直接实现。如下
public class ShapeFactory {
public Object getShape(Class cls) throws InstantiationException, IllegalAccessException {
return cls.newInstance();
}
}
public class FactoryPatternDemo {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
ObjectFactory objectFactory = new ObjectFactory();
Circle circle = (Circle)objectFactory.getObject(Circle.class);
Rectangle rectangle = (Rectangle)objectFactory.getObject(Rectangle.class);
Square square=(Square)objectFactory.getObject(Square.class);
circle.drow();
rectangle.drow();
square.drow();
}
}
单例模式
public class ObjectFactory {
private HashMap<Class,Object> hashMap=new HashMap<>();
public Object getObject(Class cls) throws InstantiationException, IllegalAccessException {
if (hashMap.containsKey(cls)) {
return hashMap.get(cls);
}
Object object=cls.newInstance();
hashMap.put(cls, object);
return object;
}
}
public class FactoryPatternDemo {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
ObjectFactory objectFactory = new ObjectFactory();
Circle circle = (Circle)objectFactory.getObject(Circle.class);
Circle circle2 = (Circle)objectFactory.getObject(Circle.class);
if(circle==circle2) {
System.out.print("他们是相同的");
}
}
}
范例
public interface Shape {
void drow();
}
public class Circle implements Shape{
@Override
public void drow() {
// TODO Auto-generated method stub
System.out.println("Circle is drowing");
}
}
public class Rectangle implements Shape{
@Override
public void drow() {
// TODO Auto-generated method stub
System.out.println("Rectangle is drowing");
}
}
public class Square implements Shape{
@Override
public void drow() {
// TODO Auto-generated method stub
System.out.println("Square is drowing");
}
}
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType==null) {
return null;
}else 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;
}
}
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory=new ShapeFactory();
Shape shape =shapeFactory.getShape("Circle");
Shape shape2 = shapeFactory.getShape("Rectangle");
Shape shape3 = shapeFactory.getShape("Square");
shape.drow();
shape2.drow();
shape3.drow();
}
}