java-工厂

2019-12-09 16:01:24来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

java-工厂

class Mouse{
    public void sayHi(){};
}

class DellMouse extends Mouse {
    @Override
    public void sayHi() {
        System.out.println("产品:戴尔鼠标");
    }
}
class HpMouse extends Mouse {
    @Override
    public void sayHi() {
        System.out.println("产品:惠普鼠标");
    }
}

class KeyBoard {
    public void kick(){};
}
class HpKeyBoard extends KeyBoard {
    @Override
    public void kick() {
        System.out.println("产品:惠普键盘");
    }
}
class DellKeyBoard extends KeyBoard {
    @Override
    public void kick() {
        System.out.println("产品:戴尔键盘");
    }
}
//总的工厂接口
interface PcFactory {
    public Mouse createMouse() ;
    public KeyBoard createKeyBoard() ;
}
class HpFactory implements PcFactory {
    @Override
    public Mouse createMouse() {
        return new HpMouse();
    }

    @Override
    public KeyBoard createKeyBoard() {
        return new HpKeyBoard();
    }
}
class DellFactory implements PcFactory {
    @Override
    public Mouse createMouse() {
        return new DellMouse();
    }
    @Override
    public KeyBoard createKeyBoard() {
        return new DellKeyBoard();
    }
}

//当需要增加一个华硕工厂时:
class AsusMouse extends Mouse {
    @Override
    public void sayHi() {
        System.out.println("产品:华硕鼠标");
    }
}
class AsusKeyBoard extends KeyBoard {
    @Override
    public void kick() {
        System.out.println("产品:华硕键盘");
    }
}
class AsusFactory implements PcFactory {
    @Override
    public Mouse createMouse() {
        return new AsusMouse();
    }
    @Override
    public KeyBoard createKeyBoard() {
        return new AsusKeyBoard();
    }
}

public class NormFactory {
    public static void main(String[] args) {
        PcFactory hpFact = new HpFactory();
        Mouse hpm = hpFact.createMouse();
        KeyBoard hpkbd = hpFact.createKeyBoard();
        
        PcFactory dellFact = new DellFactory();
        Mouse dellm = dellFact.createMouse();
        KeyBoard dellkbd = dellFact.createKeyBoard();
        
        hpm.sayHi();
        dellm.sayHi();
        
        hpkbd.kick();
        dellkbd.kick();
    }
}

打印结果如下:

产品:惠普鼠标
产品:戴尔鼠标
产品:惠普键盘
产品:戴尔键盘

原文链接:https://www.cnblogs.com/Qiav/p/12011011.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Java内存模型

下一篇:从入门到入土:Lambda完整学习指南,包教包会!