• 设计模式


    1.单例模式

    2.工厂模式
      简介:
      核心思想:有一个专门的类来负责创建实例的过程。
      优缺点:模式的核心是工厂类,这个类负责产品的创建,而客户端可以免去产品创建的责任,这实现了责任的分割。但由于工厂类集中了所有产品创建逻辑的,如果不能正常工作的话会对系统造成很大的影响。如果增加新产品必须修改工厂角色的源码。
      设计:1个接口类,若干个实现该接口的实现类,1个工厂类(工厂类实行调控功能,负责判断、控制哪个实现类被执行。工厂方法一般都是static的)。

    代码:

    public interface Fruit { 
         void grow();//生长
         void harvest();//收获 
         void plant();//种植
    }
    
    public class Apple implements Fruit{ 
        private int treeAge;
        public void grow() { 
            System.out.println("Apple is growing");
        }
        public void harvest() { 
            System.out.println("Apple has been harvested");
        }
        public void plant() { 
            System.out.println("Apple has been planted");
        }
        public int getTreeAge() {  
            return treeAge; 
        }
        public void setTreeAge(int age) {  
            this.treeAge=age; 
        }
    }
    
    public class Grape implements Fruit { 
        private boolean seedless; 
        public void grow() {  
            System.out.println("Apple is growing"); 
        } 
        public void harvest() {  
            System.out.println("Apple has been harvested"); 
        } 
        public void plant() {  
            System.out.println("Apple has been planted"); 
        } 
        public boolean getSeedless() {  
            return seedless; 
        } 
        public void setSeedless(boolean seed) {  
            this.seedless=seed; 
        }
    }
    
    public class FruitGardener { 
        public static Fruit factory(String which) throws BadFruitException {  
            if(which.equalsIgnoreCase("apple搜索"))  {   
                return new Apple();  
            } else if (which.equalsIgnoreCase("grape"))  {   
                return new Grape();  
            }  else {   
                throw new BadFruitException("Bad Fruit request");  
            }    
        }
    }
    
    public class BadFruitException extends Exception{ 
        public BadFruitException(String msg) {  
            super(msg); 
        }
    }
    
    public static void main(String[] args) { 
        try {  
            FruitGardener.factory("apple");  
            FruitGardener.factory("grape"); 
        } catch(BadFruitException e) {          
            System.out.println(e); 
        }     
    }
  • 相关阅读:
    spring注解方式AOP
    struts2 值栈的理解
    JAVA自定义注解
    JS学习随笔。
    使用Jsoup解析html网页
    Struts迭代器(iterator)遍历List常用的4种例子
    Maven 结合 Spring profile对不同的部署环境打包部署
    打印插件LODOP使用介绍
    Linux下查看CPU信息、机器型号等硬件信息
    验证码的生成和验证
  • 原文地址:https://www.cnblogs.com/thinksasa/p/4221093.html
Copyright © 2020-2023  润新知