工厂模式

/**
 *   简单工厂模式、 抽象工厂模式、工厂方法模式
 */

抽象工厂模式、工厂方法模式的区别:工厂方法模式产生单一的产品,抽象工厂模式产生多个产品

 

简单工厂模式

abstract class Computer {
    abstract void create();
}

class LenovoComputer extends Computer {
    @Override
    public void create() {
        System.out.println("联想电脑");
    }
}

class HpComputer extends Computer {
    @Override
    public void create() {
        System.out.println("惠普电脑");
    }
}

 

class ComputerFactory {
    public static Computer createComputer(String type) {
        Computer mComputer = null;
        switch (type) {
        case "lenovo":
            mComputer = new LenovoComputer();
            break;
        case "hp":
            mComputer = new HpComputer();
            break;
        }
        return mComputer;
    }
}

/*测试类*/

 

public class ComputerTest{
    public static void main(String[] args) {
        ComputerFactory.createComputer("asus").create();
    }
}

工厂方法模式

interface Move {
    void run();
}

class Dum implements Move {
    public void run() {
        System.out.println("dum");
    }
}

class Rice implements Move {
    public void run() {
        System.out.println("rice");
    }
}

/**
 * 抽象工厂
 */
abstract class AbsFactory {
    abstract Move create();
}

class DumFactory extends AbsFactory {

    Move create() {
        //Move move = new Dum();
        //move.run();
        return new Dum();
    }

}

class RiceFactory extends AbsFactory {

    Move create() {
        //Move move = new Rice();
        //move.run();
        return new Rice();
    }

}

/**
 * 这是测试
 */
public class MyFactoryTest {
    public static void main(String[] args) {
        AbsFactory absFactory=new RiceFactory();
        absFactory.create().run();
    }
}

 

posted @ 2017-09-28 21:08  yang~粪斗  阅读(107)  评论(0)    收藏  举报