简单工厂模式

。_饼干妹妹 提交于 2019-12-01 19:11:44

工厂模式
1.简单工厂模式(又称静态工厂方法模式)
2.工厂方法模式(又称多态性工厂模式)
3.抽象工厂模式(工具箱模式) 
 
 
简单工厂模式举例:
 

 

 

具体实现:
 
public class 简单工厂模式 {

    public static void main(String[] args) throws BadException {
        Friut apply = Factory.create("Apply");
        apply.grow();
    }
}

/**
 * 抽象产品
 */

interface Friut{

    /**
     * 种植
     */
    void plant();

    /**
     * 生长
     */
    void grow();

    /**
     * 收获
     */
    void harvest();
}

/**
 * 具体产品1
 */
class Apply implements Friut{

    public void plant() {
        System.out.println("Apply plant()");
    }

    public void grow() {
        System.out.println("Apply grow()");
    }

    public void harvest() {
        System.out.println("Apply harvest()");
    }
}

/**
 * 具体产品2(梨)
 */
class Pear implements Friut{

    public void plant() {
        System.out.println("Pear plant()");
    }

    public void grow() {
        System.out.println("Pear grow()");
    }

    public void harvest() {
        System.out.println("Pear harvest()");
    }
}

/**
 * 工厂类
 */
class Factory{

    public static Friut create(String type) throws BadException {
        if("Apply".equals(type)){
            return  new Apply();
        }else if("Pear".equals(type)){
            return new Pear();
        }else{
            throw new BadException("Bad Friut");
        }
    }
}

class BadException extends  Exception{

    public BadException(String msg){
        super(msg);
    }

}

 

 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!