zoukankan      html  css  js  c++  java
  • 工厂方法模式

    工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

    简单工厂模式违背了"开放-封闭"原则(再添加控制类时在简单工厂类中要修改),工厂方法模式在添加控制类时,再添加控制类对应的工厂,克服了简单工厂违背了"开放-封闭"原则。

    Leifeng.java类

    package factory;
    
    public class Leifeng {
        public void sweep(){
            System.out.println("扫地");
        }
        public void wash(){
            System.out.println("洗衣");
        }
        public void buyRice(){
            System.out.println("买米");
        }
    
    }

    Undergraduate.java类

    package factory;
    
    public class Undergraduate extends Leifeng {
    
    }

    Volunteer.java类

    package factory;
    
    public class Volunteer extends Leifeng {
    
    }

    IFacory.java类

    package factory;
    
    public abstract class IFacory {
        public abstract Leifeng createLeifeng();
    }

    UndergraduateFactory.java类

    package factory;
    
    public class UndergraduateFactory extends IFacory {
    
        @Override
        public Leifeng createLeifeng() {
            Leifeng lf = new Leifeng();
            return lf;
        }
    
    }

    VolunteerFactory.java类

    package factory;
    
    public class VolunteerFactory extends IFacory {
    
        @Override
        public Leifeng createLeifeng() {
            Leifeng lf = new Volunteer();
            return lf;
        }
    
    }

    Business.java类

    package factory;
    
    public class Business {
    
        public static void main(String[] args) {
            IFacory factory = new UndergraduateFactory();
            Leifeng lf1 = factory.createLeifeng();
            Leifeng lf2 = factory.createLeifeng();
            Leifeng lf3 = factory.createLeifeng();
            lf1.buyRice();
            lf2.sweep();
            lf3.wash();
            IFacory vfactory = new VolunteerFactory();
            Leifeng vl1 = vfactory.createLeifeng();
            Leifeng vl2 = vfactory.createLeifeng();
            Leifeng vl3 = vfactory.createLeifeng();
            vl1.buyRice();
            vl2.wash();
            vl3.sweep();
        }
    
    }
  • 相关阅读:
    PHP 高精度计算
    PHPWord使用方法
    羽毛球
    大数据(2)
    大数据(1)
    Centos 7 启动错误:XFS_WANT_CORRUPTED_GOTO 修复
    selenium 自动化工具
    python 开发技巧(0)-- 各个系统的python安装
    Yii简单使用阿里云短信教程!
    VMware虚拟机 Ubuntu 实用技巧 (2)桥接模式连接网络与网卡的配置
  • 原文地址:https://www.cnblogs.com/ccgjava/p/7037783.html
Copyright © 2011-2022 走看看