• java 简单工厂&抽象工厂


    工厂模式:就是提供一个实例化对象的接口,让子类去决定实现哪个具体对象

    1:简单工厂

    public abstract class Person {

    }
    public class XiaoLi extends Person {
    public void eat() {
    System.out.println("小李吃饭");
    }
    }
    public class XiaoMing extends Person {
    public void eat() {
    System.out.println("小明吃饭");
    }
    }
    /**
    * 简单工厂
    */
    public class SimpleFactory {
    public Person instance(String username) {
    if (username.equals("1")) {
    return new XiaoMing();
    } else if (username.equals("2")) {
    return new XiaoLi();
    }
    return null;
    }
    }
    public class SimpleTest {
    public static void main(String[] args) {
    SimpleFactory factory = new SimpleFactory();
    Person xiaoming = factory.instance("1");
    Person xiaoli = factory.instance("2");
    XiaoLi m = (XiaoLi) xiaoli;
    m.eat();
    XiaoMing l = (XiaoMing) xiaoming;
    l.eat();

    }
    }
    --------------------------------------------------------------------------------------------------------
    2:抽象工厂
    public abstract class Product {
    }
    public class MobilePhone extends Product {
    public void desc() {
    System.out.println("this is mobilephone");
    }
    }
    public class Pen extends Product {
    public void desc(){
    System.out.println("this is pen");
    }
    }
    /**
    * 抽象工厂-每个类别创建自己的工厂
    */
    public abstract class Afactory {
    public abstract Product instance();
    }
    public class MobilePhoneFactory extends  Afactory {
    @Override
    public Product instance() {
    return new MobilePhone();
    }
    }
    public class PenFactory extends Afactory {
    @Override
    public Product instance() {
    return new Pen();
    }
    }
    /**
    * 抽象工厂模式测试
    * 工厂模式:提供一个实例化对象的接口,让子类去决定实例那个具体对象
    */
    public class TestAbs {
    public static void main(String[] args) {
    Afactory penFactory = new PenFactory();
    Pen pen = (Pen) penFactory.instance();
    pen.desc();
    Afactory mobileFactory = new MobilePhoneFactory();
    MobilePhone mobilePhone = (MobilePhone) mobileFactory.instance();
    mobilePhone.desc();
    }
    }
  • 相关阅读:
    【项目管理】WBS工作分解结构
    【代理篇】内网穿透利器——Termite
    【漏洞分析】Discuz! X系列全版本后台SQL注入漏洞
    【代理篇】内网穿透利器——EarthWorm
    【漏洞复现】Apache Solr远程代码执行(CVE-2019-0193)
    【漏洞复现】Apache Solr via Velocity template远程代码执行
    【漏洞复现】PHPStudy后门
    记一次织梦cms渗透测试
    Mybatis源码手记-从缓存体系看责任链派发模式与循环依赖企业级实践
    Dubbo源码手记-服务注册
  • 原文地址:https://www.cnblogs.com/coderdxj/p/9635023.html
Copyright © 2020-2023  润新知