zoukankan      html  css  js  c++  java
  • 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();
    }
    }
  • 相关阅读:
    Return Largest Numbers in Arrays
    Title Case a Sentence
    Find the Longest Word in a String
    Check for Palindromes
    Factorialize a Number
    Reverse a String
    nodejs使用场景
    居中div,居中浮动的元素
    WebSocket解释及如何兼容低版本浏览器
    HTML5的离线储存
  • 原文地址:https://www.cnblogs.com/coderdxj/p/9635023.html
Copyright © 2011-2022 走看看