静态工厂模式

java参数设置默认值,只传递想传的参数

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        Child c1 = child.newChild(27, 80);
        String r1 = c1.toString();
        System.out.println(r1);

        Child c2 = child.newChildWithAge(22);
        String r2 = c2.toString();
        System.out.println(r2);

        Child c3 = child.newChildWithWeight(100);
        String r3 = c3.toString();
        System.out.println(r3);
    }
}

class Child {
    int age = 10;
    int weight = 30;

    public static Child newChild(int age, int weight) {
        Child child = new Child();
        child.weight = weight;
        child.age = age;
        return child;
    }

    public static Child newChildWithWeight(int weight) {
        Child child = new Child();
        child.weight = weight;
        return child;
    }

    public static Child newChildWithAge(int age) {
        Child child = new Child();
        child.age = age;
        return child;
    }

    @Override
    public String toString() {
        return "Child{" +
                "age=" + age +
                ", weight=" + weight +
                '}';
    }
}

你可能感兴趣的:(静态工厂模式)