美文网首页
创建型模式:02-工厂方法模式

创建型模式:02-工厂方法模式

作者: 综合楼 | 来源:发表于2021-06-09 21:54 被阅读0次

    类图:

    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

    相关文章

      网友评论

          本文标题:创建型模式:02-工厂方法模式

          本文链接:https://www.haomeiwen.com/subject/cxfceltx.html