ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Design Pattern - Flyweight(Java)

2019-03-23 17:56:00  阅读:299  来源: 互联网

标签:Java Chimomo Pattern Flyweight Design flyweight pointSize class chimomo


分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net 

Definition

Use sharing to support large numbers of fine-grained objects efficiently.

Participants

    The classes and/or objects participating in this pattern are:

  • Flyweight (Character)
    • Declares an interface through which flyweights can receive and act on extrinsic state.
  • ConcreteFlyweight (CharacterA, CharacterB, ..., CharacterZ)
    • Implements the Flyweight interface and adds storage for intrinsic state, if any. A ConcreteFlyweight object must be sharable. Any state it stores must be intrinsic, that is, it must be independent of the ConcreteFlyweight object's context.
  • UnsharedConcreteFlyweight (not used)
    • Not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing, but it doesn't enforce it. It is common for UnsharedConcreteFlyweight objects to have ConcreteFlyweight objects as children at some level in the flyweight object structure (as the Row and Column classes have).
  • FlyweightFactory (CharacterFactory)
    • Creates and manages flyweight objects
    • Ensures that flyweight are shared properly. When a client requests a flyweight, the FlyweightFactory objects assets an existing instance or creates one, if none exists.
  • Client (FlyweightApp)
    • Maintains a reference to flyweight(s).
    • Computes or stores the extrinsic state of flyweight(s).

Sample code in Java


This structural code demonstrates the Flyweight pattern in which a relatively small number of objects is shared many times by different clients.

/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.sample;

/**
 * The 'ConcreteFlyweight' class.
 *
 * @author Chimomo
 */
class ConcreteFlyweight extends Flyweight {

    /**
     * The operation.
     *
     * @param extrinsicState
     */
    @Override
    public void operation(int extrinsicState) {
        System.out.println("ConcreteFlyweight: " + extrinsicState);
    }

}
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.sample;

/**
 * The 'Flyweight' abstract class.
 *
 * @author Chimomo
 */
abstract class Flyweight {

    /**
     * The operation.
     *
     * @param extrinsicState
     */
    public abstract void operation(int extrinsicState);

}
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.sample;

import java.util.Hashtable;

/**
 * The 'FlyweightFactory' class.
 *
 * @author Chimomo
 */
class FlyweightFactory {

    // The flyweights.
    private Hashtable flyweights = new Hashtable();

    /**
     * Initializes a new instance of the "FlyweightFactory"class.
     */
    public FlyweightFactory() {
        this.flyweights.put("X", new ConcreteFlyweight());
        this.flyweights.put("Y", new ConcreteFlyweight());
        this.flyweights.put("Z", new ConcreteFlyweight());
    }

    /**
     * Get flyweight.
     *
     * @param key
     * @return
     */
    public Flyweight getFlyweight(String key) {
        return (Flyweight) this.flyweights.get(key);
    }

}
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.sample;

/**
 * Startup class for Structural Flyweight Design Pattern.
 *
 * @author Chimomo
 */
class Program {

    /**
     * Entry point into console application.
     *
     * @param args
     */
    public static void main(String[] args) {

        // Arbitrary extrinsic state.
        int extrinsicState = 22;
        FlyweightFactory factory = new FlyweightFactory();

        // Work with different flyweight instances.
        Flyweight fx = factory.getFlyweight("X");
        fx.operation(--extrinsicState);
        Flyweight fy = factory.getFlyweight("Y");
        fy.operation(--extrinsicState);
        Flyweight fz = factory.getFlyweight("Z");
        fz.operation(--extrinsicState);
        UnsharedConcreteFlyweight fu = new UnsharedConcreteFlyweight();
        fu.operation(--extrinsicState);
    }

}

/*
Output:
ConcreteFlyweight: 21
ConcreteFlyweight: 20
ConcreteFlyweight: 19
UnsharedConcreteFlyweight: 18
 */
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.sample;

/**
 * The 'UnsharedConcreteFlyweight' class.
 *
 * @author Chimomo
 */
class UnsharedConcreteFlyweight extends Flyweight {

    /**
     * The operation.
     *
     * @param extrinsicState Extrinsic state
     */
    @Override
    public void operation(int extrinsicState) {
        System.out.println("UnsharedConcreteFlyweight: " + extrinsicState);
    }

}

This real-world code demonstrates the Flyweight pattern in which a relatively small number of Character objects is shared many times by a document that has potentially many characters.

/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.realworld;

/**
 * The 'Flyweight' abstract class.
 *
 * @author Chimomo
 */
abstract class Character {

    // The ascent.
    protected int ascent;

    // The descent.
    protected int descent;

    // The height.
    protected int height;

    // The point size.
    protected int pointSize;

    // The symbol.
    protected char symbol;

    // The width.
    protected int width;

    /**
     * Display.
     *
     * @param pointSize
     */
    public abstract void display(int pointSize);

}
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.realworld;

/**
 * The 'ConcreteFlyweight' class.
 *
 * @author Chimomo
 */
class CharacterA extends Character {

    /**
     * Initializes a new instance of the "CharacterA" class.
     */
    public CharacterA() {
        this.symbol = 'A';
        this.height = 100;
        this.width = 120;
        this.ascent = 70;
        this.descent = 0;
    }

    /**
     * Display.
     *
     * @param pointSize
     */
    @Override
    public void display(int pointSize) {
        this.pointSize = pointSize;
        System.out.println(this.symbol + " (point size " + this.pointSize + ")");
    }

}
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.realworld;

/**
 * The 'ConcreteFlyweight' class.
 *
 * @author Chimomo
 */
class CharacterB extends Character {

    /**
     * Initializes a new instance of the "CharacterB" class.
     */
    public CharacterB() {
        this.symbol = 'B';
        this.height = 100;
        this.width = 140;
        this.ascent = 72;
        this.descent = 0;
    }

    /**
     * Display.
     *
     * @param pointSize
     */
    @Override
    public void display(int pointSize) {
        this.pointSize = pointSize;
        System.out.println(this.symbol + " (point size " + this.pointSize + ")");
    }
    
}
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.realworld;

import java.util.HashMap;
import java.util.Map;

/**
 * The 'FlyweightFactory' class.
 *
 * @author Chimomo
 */
class CharacterFactory {

    // The characters.
    private Map<java.lang.Character, Character> characters = new HashMap<>();

    /**
     * Get character.
     *
     * @param key
     * @return
     */
    public Character getCharacter(char key) {

        // Uses "lazy initialization".
        Character character = null;

        if (this.characters.containsKey(key)) {
            character = this.characters.get(key);
        } else {
            switch (key) {
                case 'A':
                    character = new CharacterA();
                    break;

                case 'B':
                    character = new CharacterB();
                    break;

                // ...

                case 'Z':
                    character = new CharacterZ();
                    break;
            }
            this.characters.put(key, character);
        }
        return character;
    }

}
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.realworld;

/**
 * The 'ConcreteFlyweight' class.
 *
 * @author Chimomo
 */
class CharacterZ extends Character {

    /**
     * Initializes a new instance of the "CharacterZ" class.
     */
    public CharacterZ() {
        this.symbol = 'Z';
        this.height = 100;
        this.width = 100;
        this.ascent = 68;
        this.descent = 0;
    }

    /**
     * Display.
     *
     * @param pointSize
     */
    @Override
    public void display(int pointSize) {
        this.pointSize = pointSize;
        System.out.println(this.symbol + " (point size " + this.pointSize + ")");
    }

}
/*
 *  Chimomo's Blog: https://blog.csdn.net/chimomo/
 */
package chimomo.learning.java.designpattern.flyweight.realworld;

/**
 * Startup class for Real-World Flyweight Design Pattern.
 *
 * @author Chimomo
 */
class Program {

    /**
     * Entry point into console application.
     *
     * @param args Arguments
     */
    public static void main(String[] args) {

        // Build a document with text.
        final String document = "AAZZBBZB";
        char[] chars = document.toCharArray();
        CharacterFactory factory = new CharacterFactory();

        // Extrinsic state.
        int pointSize = 10;

        // For each character use a flyweight object.
        for (char c : chars) {
            pointSize++;
            Character character = factory.getCharacter(c);
            character.display(pointSize);
        }
    }

}

/*
Output:
A (point size 11)
A (point size 12)
Z (point size 13)
Z (point size 14)
B (point size 15)
B (point size 16)
Z (point size 17)
B (point size 18)
 */

标签:Java,Chimomo,Pattern,Flyweight,Design,flyweight,pointSize,class,chimomo
来源: https://blog.csdn.net/chimomo/article/details/80975442

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有