设计模式

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); 
    }     
}
原文地址:https://www.cnblogs.com/thinksasa/p/4221093.html