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;
        }
    
    }
  • 相关阅读:
    ubuntu基本命令篇13用户管理
    网易邮箱繁体字信件乱码解决
    ubuntu基本命令篇16网络管理
    Ubuntu 10.04的安装
    DotNetNuke模块开发(一)
    查询进程打开的文件(转)
    Shell 的变量(转)
    Boot loader: Grub进阶(转)
    bash的通配符与特殊符号
    shell下的作业管理(转)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13959827.html
Copyright © 2011-2022 走看看