zoukankan      html  css  js  c++  java
  • [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;
        }
    
    }
  • 相关阅读:
    洛谷 U140360 购物清单
    洛谷 U140359 批量处理
    洛谷 U140358 操作系统
    洛谷U140357 Seaway连续
    洛谷 U141394 智
    洛谷 U141387 金
    CF1327F AND Segments
    刷题心得—连续位运算题目的小技巧
    CF743C Vladik and fractions
    洛谷 P6327 区间加区间sin和
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13959827.html
Copyright © 2011-2022 走看看