设计模式
设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。
设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了重用代码、让代码更容易被他人理解、保证代码可靠性。
工厂模式
工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
工厂模式的意图在于定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
代码示例:
//定义一个接口
public interface Shape {
void draw();
}
//定义三个类实现接口
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
创建一个工厂,生成基于给定信息的实体类的对象 ,使用该工厂,通过传递类型信息来获取实体类的对象。
public class ShapeFactory {
//使用 getShape 方法获取形状类型的对象
public Shape getShape(String str){
if (str == null){
return null;
}
if (str.equals("Circle")){
return new Circle();
}else if (str.equals("Square")){
return new Square();
}else if (str.equals("Rectangle")){
return new Rectangle();
}else {
return null;
}
}
}
public class ShapeFactoryDemo {
public static void main(String[] args) {
//使用该工厂,通过传递Shape类信息来获取实体类的对象。
ShapeFactory shapeFactory = new ShapeFactory();
//获取 Circle 的对象,并调用它的 draw 方法
Shape circle = shapeFactory.getShape("Circle");
circle.draw();
Shape square = shapeFactory.getShape("Square");
square.draw();
Shape rectangle = shapeFactory.getShape("Rectangle");
rectangle.draw();
}
}
代码执行结果:
如果还是不太明白,可以看看这篇文章--> 工厂模式