Java工廠模式和建造者模式是兩種常用的設(shè)計(jì)模式。在開發(fā)過程中,這兩個(gè)模式可以幫助開發(fā)者更好地組織和管理代碼。
Java工廠模式是指將對(duì)象的創(chuàng)建過程封裝在一個(gè)工廠類中,通過這個(gè)工廠類來創(chuàng)建對(duì)象。這種方式可以避免在代碼中直接使用new關(guān)鍵字創(chuàng)建對(duì)象,從而降低代碼的耦合性,便于維護(hù)和擴(kuò)展。下面是一個(gè)使用Java工廠模式創(chuàng)建對(duì)象的例子:
public interface Animal { void makeSound(); } public class Dog implements Animal { public void makeSound() { System.out.println("Wang Wang!"); } } public class Cat implements Animal { public void makeSound() { System.out.println("Miao Miao!"); } } public class AnimalFactory { public static Animal createAnimal(String type) { if(type.equals("Cat")) { return new Cat(); } else if(type.equals("Dog")) { return new Dog(); } else { return null; } } } public class Test { public static void main(String[] args) { Animal animal1 = AnimalFactory.createAnimal("Cat"); Animal animal2 = AnimalFactory.createAnimal("Dog"); animal1.makeSound(); animal2.makeSound(); } }
建造者模式是指將一個(gè)復(fù)雜的對(duì)象的構(gòu)建過程分解成多個(gè)簡(jiǎn)單的步驟,然后將這些步驟封裝在一個(gè)Builder類中,最終通過Builder類來構(gòu)建該對(duì)象。這種方式可以使得構(gòu)建代碼和表示代碼分離,便于代碼的維護(hù)和擴(kuò)展。下面是一個(gè)使用Java建造者模式構(gòu)建對(duì)象的例子:
public class Person { private String name; private int age; private String gender; public static class Builder { private String name = ""; private int age = 0; private String gender = ""; public Builder setName(String name) { this.name = name; return this; } public Builder setAge(int age) { this.age = age; return this; } public Builder setGender(String gender) { this.gender = gender; return this; } public Person build() { Person person = new Person(); person.name = name; person.age = age; person.gender = gender; return person; } } private Person() {} public String getName() { return name; } public int getAge() { return age; } public String getGender() { return gender; } } public class Test { public static void main(String[] args) { Person person = new Person.Builder() .setName("張三") .setAge(18) .setGender("男") .build(); System.out.println(person.getName() + ", " + person.getAge() + ", " + person.getGender()); } }