AdSense

網頁

2024/11/26

Spring Boot factory bean polymorphism

Spring Boot中透過工廠(factory bean)實現bean的多態(polymorphism)。


範例

例如貓Cat和狗Dog類別實現動物Animal介面。

動物們的列舉。

AnimalType

public enum AnimalType {
    CAT,
    DOG,
}

Animal介面。

Animal

package com.abc.demo.animal;

import com.abc.demo.enumeration.AnimalType;

public interface Animal {
    AnimalType getType();
    void action();
}

貓bean。

Cat

package com.abc.demo.animal;

import com.abc.demo.enumeration.AnimalType;
import org.springframework.stereotype.Component;

@Component("cat")
public class Cat implements Animal{
    @Override
    public AnimalType getType() {
        return AnimalType.CAT;
    }

    @Override
    public void action() {
        System.out.println("meow");
    }
}

狗bean。

Dog

package com.abc.demo.animal;

import com.abc.demo.enumeration.AnimalType;
import org.springframework.stereotype.Component;

@Component("dog")
public class Dog implements Animal{
    @Override
    public AnimalType getType() {
        return AnimalType.DOG;
    }

    @Override
    public void action() {
        System.out.println("woof");
    }
}

AnimalFactory為工廠bean,內裝有CatDog bean,透過呼叫getAnimal()輸入動物列舉來取得對應的實例。

AnimalFactory

package com.abc.demo.factory;

import com.abc.demo.animal.Animal;
import com.abc.demo.enumeration.AnimalType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.EnumMap;
import java.util.List;

@Component
public class AnimalFactory {
    private final EnumMap<AnimalType, Animal> animalsMap;

    @Autowired
    public AnimalFactory(List<Animal> animals) {
        this.animalsMap = new EnumMap<>(AnimalType.class);
        for (Animal animal: animals) {
            this.animalsMap.put(animal.getType(), animal);
        }
    }

    public Animal getAnimal(AnimalType animalType) {
        return this.animalsMap.get(animalType);
    }

}

Zoo類別示範如何用工廠bean來產生對應的實例並執行動作,在此體現Animal的多態性(polymorphism)。

Zoo

package com.abc.demo;

import com.abc.demo.enumeration.AnimalType;
import com.abc.demo.factory.AnimalFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Zoo {

    @Autowired
    private AnimalFactory factory;

    public void play() {
        factory.getAnimal(AnimalType.CAT).action();
        factory.getAnimal(AnimalType.DOG).action();
    }

}


測試

在Spring Boot入口取得Zoo的實例並執行其方法。

DemoApplication

package com.abc.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
        Zoo zoo = ctx.getBean(Zoo.class);
        zoo.play();
    }

}

執行結果如下。

meow
woof


沒有留言:

AdSense