Simple Factory and Factory Method
Simple Factory Example
// Simple Factory
class AnimalFactory {
public Animal getAnimal(String type) {
if ("Dog".equalsIgnoreCase(type)) {
return new Dog();
} else if ("Cat".equalsIgnoreCase(type)) {
return new Cat();
}
return null;
}
}
interface Animal {
void speak();
}
class Dog implements Animal {
public void speak() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void speak() {
System.out.println("Meow");
}
}
// Client code
public class Main {
public static void main(String[] args) {
AnimalFactory factory = new AnimalFactory();
Animal myDog = factory.getAnimal("Dog");
myDog.speak(); // Outputs: Woof
}
}In the Simple Factory example, the AnimalFactory class decides which type of Animal to instantiate based on the input parameter.
在简单工厂示例中, AnimalFactory 类根据输入参数决定实例化哪种类型的 Animal 。
Factory Method Example
// Factory Method
interface Animal {
void speak();
}
class Dog implements Animal {
public void speak() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void speak() {
System.out.println("Meow");
}
}
abstract class AnimalCreator {
// Factory Method
public abstract Animal createAnimal();
}
class DogCreator extends AnimalCreator {
public Animal createAnimal() {
return new Dog();
}
}
class CatCreator extends AnimalCreator {
public Animal createAnimal() {
return new Cat();
}
}
// Client code
public class Main {
public static void main(String[] args) {
AnimalCreator creator = new DogCreator();
Animal myDog = creator.createAnimal();
myDog.speak(); // Outputs: Woof
}
}In the Factory Method example, the creation of Animal objects is deferred to subclasses (DogCreator and CatCreator) that implement the createAnimal method defined in the abstract AnimalCreator class. This allows for greater flexibility and adheres to the open/closed principle, as adding a new animal type does not require modifying existing code, just adding new subclasses.
在 "工厂方法 "示例中, Animal 对象的创建被推迟到了实现抽象 AnimalCreator 类中定义的 createAnimal 方法的子类( DogCreator 和 CatCreator )。这样可以提高灵活性并遵守开放/封闭原则,因为添加新的动物类型不需要修改现有代码,只需添加新的子类即可。
These examples demonstrate the core difference between the two patterns: the Simple Factory uses a single class to create instances of many types, while the Factory Method pattern uses inheritance and lets subclasses decide which class to instantiate.
这些示例展示了两种模式的核心区别:简单工厂使用单个类创建多种类型的实例,而工厂方法模式使用继承,让子类决定实例化哪个类。
似乎 AnimalCreator 抽象类也可以用接口表示
// Factory Method with Interface
interface Animal {
void speak();
}
class Dog implements Animal {
public void speak() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void speak() {
System.out.println("Meow");
}
}
interface AnimalCreator {
// Factory Method
Animal createAnimal();
}
class DogCreator implements AnimalCreator {
public Animal createAnimal() {
return new Dog();
}
}
class CatCreator implements AnimalCreator {
public Animal createAnimal() {
return new Cat();
}
}
// Client code
public class Main {
public static void main(String[] args) {
AnimalCreator creator = new DogCreator();
Animal myDog = creator.createAnimal();
myDog.speak(); // Outputs: Woof
}
}既然可以使用接口,那为何要选择抽象类呢?
Choosing between using an abstract class or an interface for the creator in the Factory Method pattern depends on your specific needs. If you need to share code among the creators (e.g., common methods or fields), an abstract class might be more appropriate. If you need maximum flexibility and the ability to implement multiple patterns or interfaces, then using an interface for the creator would be the better choice.
在工厂方法模式中,为创建者选择使用抽象类还是接口取决于您的具体需求。如果需要在创建者之间共享代码(例如,共享方法或字段),那么使用抽象类可能更合适。如果您需要最大限度的灵活性和实现多种模式或接口的能力,那么为创建者使用接口将是更好的选择。
例如下面的代码,就需要选择抽象类而不是接口了
interface Animal {
void speak();
}
class Dog implements Animal {
public void speak() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void speak() {
System.out.println("Meow");
}
}
// Abstract class with shared code
abstract class AnimalCreator {
// Factory Method
public abstract Animal createAnimal();
// Shared method among creators
protected void logCreation(String animalType) {
System.out.println(animalType + " created.");
}
}
class DogCreator extends AnimalCreator {
public Animal createAnimal() {
Animal animal = new Dog();
logCreation("Dog"); // Using the shared method
return animal;
}
}
class CatCreator extends AnimalCreator {
public Animal createAnimal() {
Animal animal = new Cat();
logCreation("Cat"); // Using the shared method
return animal;
}
}
// Client code
public class Main {
public static void main(String[] args) {
AnimalCreator dogCreator = new DogCreator();
Animal myDog = dogCreator.createAnimal();
myDog.speak(); // Outputs: Woof and logs "Dog created."
AnimalCreator catCreator = new CatCreator();
Animal myCat = catCreator.createAnimal();
myCat.speak(); // Outputs: Meow and logs "Cat created."
}
}In this example, the abstract AnimalCreator class defines a logCreation method that logs a message to the console whenever an animal is created. Each concrete creator (DogCreator and CatCreator) calls this shared method after creating an animal, thus avoiding code duplication across creators.
在本示例中,抽象 AnimalCreator 类定义了一个 logCreation 方法,该方法可在创建动物时向控制台记录一条消息。每个具体创建者( DogCreator 和 CatCreator )在创建动物后都会调用此共享方法,从而避免了创建者之间代码的重复。
This approach demonstrates how abstract classes can be beneficial in the Factory Method pattern by allowing shared code and functionality to be centralized, which promotes code reuse and simplifies maintenance.
这种方法展示了抽象类在工厂方法模式中的优势,它允许集中共享代码和功能,从而促进代码重用并简化维护。
Create With GPT-4
评论已关闭