• Java之静态工厂方法


    很多书中都提到了创建对象的时候尽量不要去直接用构造器去new,而是采用静态工厂方法,去代替构造器

    初时我还不太明白,后来看了几篇优秀的文章之后,豁然开朗,记下来供以后查看。

    假设有这样一个类:

    package com.example.demo;
    
    public class Dog {
        private String name;
    
        private String color;
    
        private int age;
    
        public Dog() {
        }
    
        public Dog(String name) {
            this.name = name;
        }
    
        public Dog(String name, String color, int age) {
            this.name = name;
            this.color = color;
            this.age = age;
        }
    }

    问题在于以后我想增加一个只有参数只有狗的颜色的构造器,但是已经没办法加了,因为和参数是name的构造器冲突了。

    但是如果我用静态工厂方法来写,这个问题就解决了:

    package com.example.demo;
    
    public class Dog {
        private String name;
    
        private String color;
    
        private int age;
    
        private Dog() {
        }
    
        public static Dog newDogWithAllParam(String name, String color, int age) {
            Dog dog = new Dog();
            dog.name = name;
            dog.age = age;
            dog.color = color;
            return dog;
        }
    
        public static Dog newDogWithName(String name) {
            Dog dog = new Dog();
            dog.name = name;
            return dog;
        }
    
        public static Dog newDogWithColor(String color) {
            Dog dog = new Dog();
            dog.color = color;
            return dog;
        }
    // Getters & Setters
    }

    使用静态工厂方法的好处有很多,比如下面这两点:

    1.每次新建对象的时候,只需要调度需要的方法就可以了,而且每个方法有不同的“名字”,通过名字我可以清楚的知道我是用什么属性去创建的对象

    2.使用静态工厂方法不必每次都创建一个新对象,因为static是属于类的,因此不管创建多少个对象,一个类始终只有一个static对象,这样当你不得不去创建大量对象的时候防止内存消耗

  • 相关阅读:
    javascript高级知识分析——灵活的参数
    javascript高级知识分析——实例化
    javascript高级知识分析——上下文
    javascript高级知识分析——作为对象的函数
    javascript高级知识分析——函数访问
    javascript高级知识分析——定义函数
    new到底做了什么?
    JavaScript中的计时器原理
    解析Function.prototype.bind
    将类数组对象(array-like object)转化为数组对象(Array object)
  • 原文地址:https://www.cnblogs.com/caotao0918/p/12072286.html
Copyright © 2020-2023  润新知