首页 > 编程语言 > 详细

Java享元模式(思维导图)

时间:2019-08-22 00:11:29      阅读:125      评论:0      收藏:0      [点我收藏+]

技术分享图片

图1 享元模式【点击查看图片】

1,实体接口与类

package com.cnblogs.mufasa.demo2;

public interface People {
    void say();
}

class Person implements People{
    private String country;
    private boolean gender;
    private int age;
    private final String[] StrGender={"Male","Female"};

    public Person(String country) {
        this.country=country;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public void say() {
        System.out.println("I was "+age+" years old,a "+StrGender[(gender?0:1)]+",came from "+country);
    }
}

 

2,工厂类

package com.cnblogs.mufasa.demo2;

import java.util.HashMap;

public class PersonFactory {
    private static final HashMap<String, People> peopleHashMap = new HashMap<>();//和单例模式有点像
    public static People getPerson(String country) {
        People people = (People) peopleHashMap.get(country);
        if(people==null){
            people=new Person(country);
            peopleHashMap.put(country,people);
            System.out.println("Creating person of country : " + country);
        }
        return people;
    }
}

 

3,享元类

package com.cnblogs.mufasa.demo2;

public class FlyweightPatternDemo {
    private static final String[] COUNTRY={ "China", "Russia", "America", "England", "France" };

    public static void main(String[] args) {
        for(int i=0; i < 20; ++i) {
            Person pr =(Person) PersonFactory.getPerson(getCountry());
            pr.setAge(getAge());
            pr.setGender(getGender());
            pr.say();
        }
    }


    private static String getCountry() {//获取国家信息
        return COUNTRY[(int)(Math.random()*COUNTRY.length)];
    }
    private static boolean getGender() {
        return ((int)(Math.random()*2 )==0? true : false);
    }
    private static int getAge() {
        return (int)(Math.random()*100);
    }
}

 

Java享元模式(思维导图)

原文:https://www.cnblogs.com/Mufasa/p/11391667.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!