gpt4 book ai didi

java - 实现设计模式和 Spring MVC

转载 作者:搜寻专家 更新时间:2023-11-01 03:46:04 26 4
gpt4 key购买 nike

如何将单例设计模式与工厂设计模式结合使用?在spring MVC中我们可以通过多少种方式在 Controller 和jsp之间进行通信?

最佳答案

您可以在工厂方法旁边使用单例,方法是在工厂模式接口(interface)中实现的每个方法中应用单例模式

(singleton inside methods(只能存在一个实例的类)/工厂植入在服务的接口(interface)中,创建多个派生类(方法)的实例)

interface ImageReader {
DecodedImage getDecodeImage();
}

class DecodedImage {
private String image;
public DecodedImage(String image) {this.image = image;}
@Override
public String toString() {return image + ": is decoded";}
}

class GifReader implements ImageReader {
private DecodedImage decodedImage;
public GifReader(String image) {
this.decodedImage = new DecodedImage(image);}

@Override
public DecodedImage getDecodeImage() {return decodedImage;}
}
//this is a method implementing singleton inside a factory pattern
public class Singleton implements ImageReader {
private Singleton() {}
private static class SingletonHolder {private static final Singleton INSTANCE = new
Singleton();}
public static Singleton getInstance() {return SingletonHolder.INSTANCE;}
}


public class FactoryMethodDemo {
public static void main(String[] args) {
DecodedImage decodedImage;
ImageReader reader = null;
String image = args[0];
String format = image.substring(image.indexOf('.') + 1, (image.length()));
if (format.equals("gif")) {
reader = new GifReader(image);
}
if (format.equals("singleton")) {
reader = new Singleton();
}

assert reader == decodedImage;
decodedImage = reader.getDecodeImage();
System.out.println(decodedImage);
}
}

这个网站也有更多的例子https://sourcemaking.com/design_patterns

关于java - 实现设计模式和 Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54060825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com