我正在学习春季框架。我从网站上阅读了许多教程,但我无法得到他们的解释。请简单地以简单的方式向我解释。
-
在这里,我放置了工厂设计模式以实现松散的耦合,以及我们在春季也使用这种设计模式。
-
我无法明白这一点(句子("此模式提供了创建对象的最佳方法之一"。
public interface Shape { void draw(); } public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } 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; } } 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(); } }
输出:
Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.
在这里您使用经典工厂,该工厂在每个调用中创建新实例。但是工厂错过了两点:getShape()
应该提供静态方法,而工厂类不应超过一次。
使用单身顿和静态方法进行工厂类带来一些缺点:在测试期间进行嘲笑更为复杂,工厂增加了其职责(这是单身人士,但也是工厂类别(,高耦合在同类的类别之间创建应用程序:客户端类和工厂。
春季提供的依赖注入(但并不孤单(解决了这些问题。
春天确实扮演了工厂的角色,春季也是春天的关注。
在春季,您有一些方法可以做足够相似的事情:
-
使用工厂 - 湾和工厂方法。您有XML和Java版本。
XML的方式是XML方式:详细说明,如果您更喜欢直接注释您的类,而不是创建间接式来读取二手弹簧配置。
Java版本没有间接缺点,但是由于您的工厂类必须实现SpringFactoryBean
接口。 -
使用
prototype
范围注释的经典弹簧豆。
春季的等效物可能是:
@Bean
@Scope("prototype")
public Shape shape(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;
}
以任何方式,您应该使用Object getBean(String name, Object... args)
或ApplicationContext
的CC_4传输shapeType
参数。
例如:
Shape shape = (Shape) applicationContext.getBean("shape", "CIRCLE");
春季:您可以将您的工厂声明为@Component
或@Bean
,然后将其自动到需要它的任何位置。
因此,您将避免调用其构造函数,并且在应用程序开始时将将工厂的单例实例加载到ApplicationContext中。
工厂:工厂的目的是将实例创建的所有逻辑包裹到工厂的方法中,以简化对象创建。如果您在许多地方需要多次相同的对象,则可以避免构造函数调用并将值传递给setter,但只能调用工厂的单个方法。