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;
        }
    
    }
  • 相关阅读:
    localhost和本机IP和127.0.0.1之间的区别
    git客户端msysGit和TortoiseGit使用
    JS正则
    css中外边距
    css定位浮动总结
    Teleport Ultra 抓包工具
    编程实践心得与设计思想
    Java 读写Properties配置文件
    如何成为一个优秀的DBA
    对DB2常见错误的列举以及破解方案
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13959827.html
Copyright © 2011-2022 走看看