实现设计模式和Spring MVC

4

如何使用单例设计模式和工厂设计模式?在Spring MVC中,控制器和JSP之间有哪些通信方式?

1个回答

0

您可以在工厂方法中使用单例模式,通过在工厂模式接口中实现每个方法时应用单例模式。

(在方法内部应用单例模式(只能存在一个实例的类)/ 工厂实现在服务接口中,创建多个派生类(方法)的实例)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接