类图:
image.png
示例代码:
image.png
package com.zhs.design.factory.method.factory;
----------------------------------------------------------------
public interface PictureReaderFactory {
PictureReader creatReader();
}
----------------------------------------------------------------
public class GifReaderFactory implements PictureReaderFactory {
@Override
public PictureReader creatReader() {
return new GifReader();
}
}
----------------------------------------------------------------
public class JpgReaderFactory implements PictureReaderFactory {
@Override
public PictureReader creatReader() {
return new JpgReader();
}
}
----------------------------------------------------------------
public class PngReaderFactory implements PictureReaderFactory {
@Override
public PictureReader creatReader() {
return new PngReader();
}
}
package com.zhs.design.factory.method.reader;
----------------------------------------------------------------
public interface PictureReader {
String read(String png);
}
----------------------------------------------------------------
public class GifReader implements PictureReader {
public GifReader() {
System.out.println("创建GIF图片读取器成功!");
}
@Override
public String read(String gif) {
return "读取的GIF图片的内容为:"+gif;
}
}
----------------------------------------------------------------
public class JpgReader implements PictureReader {
public JpgReader() {
System.out.println("创建JPG图片读取器成功!");
}
@Override
public String read(String jpg) {
return "读取的JPG图片的内容为:"+jpg;
}
}
----------------------------------------------------------------
public class PngReader implements PictureReader {
public PngReader() {
System.out.println("创建PNG图片读取器成功!");
}
@Override
public String read(String png) {
return "读取的PNG图片的内容为:"+png;
}
}
package com.zhs.design.factory.method;
public class Client {
public static void main(String[] args) {
PictureReaderFactory factory = new GifReaderFactory();
PictureReader reader = factory.creatReader();
System.out.println(reader.read("我是猫咪图片"));
}
}
运行结果:
image.png
网友评论