• 工厂模式


    设计模式:就是大佬经验的总结。

    设计模式的分类:

      (1)创建型-->创建对象

      (2)结构型-->对象的组成

      (3)行为型-->对象的功能

    简单工厂模式:又叫静态工厂方法模式,它定义一个具体的工厂类负责创建一些类的实例。

    优点:客户端不需要负责对象的创建,从而明确了各个类的职责。

    缺点:这个工厂类负责所有对象的创建,如果有新的对象增加,或者某些对象的创建方式不同,就需要不断的修改工厂类,不利于后期的维护。

    abstract class Animal {
        
        public abstract void eat();
    }
    
    class Dog extends Animal {
        
        @Override
        public void eat() {
            System.out.println("dog gnaw bone.");
        }
    }
    
    class Cat extends Animal {
        
        @Override
        public void eat() {
            System.out.println("cat eat fish.");
        }
    }
    
    class AnimalFactory {
        
        private AnimalFactory() {}
        
        public static Animal createAnimal(String type) {
            if ("cat".equals(type)) {
                return new Cat();
            } else if ("dog".equals(type)) {
                return new Dog();
            } else {
                return null;
            }
        }
    }
    
    public class Test {
        
        public static void main(String[] args) {
            
            Animal cat = AnimalFactory.createAnimal("cat");
            
            if (cat != null) {
                cat.eat();
            } else {
                System.out.println("this animal is not available for the time being.");
            }
        }
    }

    工厂方法模式:抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。
    优点:客户端不需要再负责对象的创建,从而明确了各个类的职责,如果有新的对象添加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性。

    缺点:需要额外的代码编写,增加了工作量。

    abstract class Animal {
        
        public abstract void eat();
    }
    
    interface Factory {
        
        public abstract Animal createAnimal();
    }
    
    class Dog extends Animal {
        
        @Override
        public void eat() {
            System.out.println("dog gnaw bone.");
        }
    }
    
    class DogFactory implements Factory {
        
        @Override
        public Animal createAnimal() {
            return new Dog();
        }
    }
    
    public class Test {
        
        public static void main(String[] args) {
            
            Factory factory = new DogFactory();
            Animal dog = factory.createAnimal();
            dog.eat();
        }
    }
  • 相关阅读:
    hibernate建表默认为UTF-8编码
    XML和JSON
    chrome 模拟发送请求的方法
    什么时候需要使用缓存?
    eclipse中查找类、方法及变量被引用的地方
    用户内容与商业
    2019第48周日
    ajax与重定向
    ifream
    Windows下找到JVM占用资源高的线程
  • 原文地址:https://www.cnblogs.com/chen-cai/p/9943991.html
Copyright © 2020-2023  润新知