A: 创造性模式

1. 工厂方法模式(FactoryMethod)

1.1 类图

设计模式 UML & java code

1.2 代码1

public interface Pet
{
    public String petSound();
}

public class Cat implements Pet {
    @Override
    public String petSound() {
        return "Meaw Meaw...";
    }
}

public class Dog implements Pet {
    @Override
    public String petSound() {
        return "Bow Bow...";
    }
}

public class PetFactory {
    public Pet getPet(String petType){
        Pet pet = null;
        if("Bow".equals(petType)){
            pet = new Dog();
        }else if("Meaw".equals(petType)){
            pet = new Cat();
        }
        return pet;
    }
}

public class SampleFactoryMethod {
    public static void main(String[] args){
        PetFactory factory = new PetFactory();
        Pet pet = factory.getPet("Bow");
        System.out.println(pet.petSound());
    }
}
View Code

相关文章:

  • 2021-04-11
  • 2022-01-14
  • 2021-06-20
  • 2021-06-10
  • 2021-11-27
  • 2021-12-01
  • 2022-12-23
猜你喜欢
  • 2021-12-28
  • 2021-10-24
  • 2022-12-23
  • 2021-09-02
  • 2021-12-13
  • 2021-07-17
  • 2021-09-22
相关资源
相似解决方案