• [Spring] Factory Pattern


    Coding again the interface.

    interface:

    package com.frankmoley.lil.designpatternsapp.factory;
    
    public interface Pet {
        void setName(String name);
        String getName();
        String getType();
        boolean isHungry();
        void feed();
    }

    Factory:

    package com.frankmoley.lil.designpatternsapp.factory;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class PetFactory {
        public Pet createPet(String animalType){
            switch(animalType.toLowerCase()){
                case "dog":
                    return new Dog();
                case "cat":
                    return new Cat();
                default:
                    throw new UnsupportedOperationException("unknown animal type");
            }
        }
    }

    @Component added to tell this class should be managed by Spring, so later we can use @Autowired.

    Class implements the interface:

    package com.frankmoley.lil.designpatternsapp.factory;
    
    public class Cat implements Pet {
        private String name;
        private boolean hungry;
    
        public Cat(){
            super();
            this.hungry = true;
        }
    
        @Override
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String getName() {
            return this.name;
        }
    
        @Override
        public String getType() {
            return "CAT";
        }
    
        @Override
        public boolean isHungry() {
            return this.hungry;
        }
    
        @Override
        public void feed() {
            this.hungry = false;
        }
    }

    Controller:

    @RestController
    @RequestMapping("/")
    public class AppController {
        @Autowired
        private PetFactory petFactory;
    
        @GetMapping
        public String getDefault(){
            return "{"message": "Hello World"}";
        }
    
        @PostMapping("adoptPet/{type}/{name}")
        public Pet adoptPet(@PathVariable String type, @PathVariable String name){
            Pet pet = this.petFactory.createPet(type);
            pet.setName(name);
            pet.feed();
            return pet;
        }
    
    }
  • 相关阅读:
    javaScript中的find()方法和返回数据的内存指向
    高级函数 filter map reduce 的使用
    for ... in and for ... of 理解
    git 解决冲突问题
    H5内唤醒百度、高德APP
    HTML 5标准中最新引入的template标签介绍
    jquery选择器使用
    ajax封装函数
    常用正则表达式
    JS-----事件、image对象
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13959827.html
Copyright © 2020-2023  润新知