zoukankan      html  css  js  c++  java
  • 2_flyweight, 轻量化模式

    ### instanced rendering.
    send shared data to gpu just once
        mesh, texture, leaves
    push every instance’s unique data
        position, color, scale
    
    With a single draw call, an entire forest grows.
    
    unity3d
        Using instances of a prefab automatically are using the same mesh and material.
    
    
    ### the flyweight pattern
    
    当拥有大量同样的obj时,则需要更多的轻量化
    
    把一个ojb分成两类
        1: intrinsic state, 共享的数据, content—free stuff
        2: extrinsic state, 独有的数据,
    
    example
    
    ```
    intrinsic state: 世界包含若干种地形
    extrinsic state: 不同的位置具有不同的地形,指向相应的地形
    
    class Terrain
    {
    public:
      Terrain(int movementCost,
              bool isWater,
              Texture texture)
      : movementCost_(movementCost),
        isWater_(isWater),
        texture_(texture)
      {}
    
      int getMovementCost() const { return movementCost_; }
      bool isWater() const { return isWater_; }
      const Texture& getTexture() const { return texture_; }
    
    private:
      int movementCost_;
      bool isWater_;
      Texture texture_;
    };
    
    class World
    {
    public:
      World()
      : grassTerrain_(1, false, GRASS_TEXTURE),
        hillTerrain_(3, false, HILL_TEXTURE),
        riverTerrain_(2, true, RIVER_TEXTURE)
      {}
    
    private:
      Terrain grassTerrain_;
      Terrain hillTerrain_;
      Terrain riverTerrain_;
    
      // Other stuff...
    };
    
    void World::generateTerrain()
    {
      // Fill the ground with grass.
      for (int x = 0; x < WIDTH; x++)
      {
        for (int y = 0; y < HEIGHT; y++)
        {
          // Sprinkle some hills.
          if (random(10) == 0)
          {
            tiles_[x][y] = &hillTerrain_;
          }
          else
          {
            tiles_[x][y] = &grassTerrain_;
          }
        }
      }
    
      // Lay a river.
      int x = random(WIDTH);
      for (int y = 0; y < HEIGHT; y++) {
        tiles_[x][y] = &riverTerrain_;
      }
    }
    
    const Terrain& World::getTile(int x, int y) const
    {
      return *tiles_[x][y];
    }
    
    int cost = world.getTile(2, 3).getMovementCost();
    
    
    ```
    ###其他应用
        工厂方法
        对象池
        状态机
  • 相关阅读:
    Linux Centos7配置mysql8.0数据库
    Linux Centos7配置ftp服务器
    线程池工具ThreadPoolExecutor
    Layui 实现input 输入和选择
    canvas验证码实现
    弹性布局flex 介绍
    java EE 新手入门了解
    java web工程web.xml介绍
    js 数组常用的一些方法
    详解为什么需要重写hashcode 和 equals 方法
  • 原文地址:https://www.cnblogs.com/lightlfyan/p/4224373.html
Copyright © 2011-2022 走看看