What are enums and why are they useful?

后端 未结 27 1362
一整个雨季
一整个雨季 2020-11-22 07:06

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits

27条回答
  •  攒了一身酷
    2020-11-22 07:20

    As for me to make the code readable in future the most useful aplyable case of enumeration is represented in next snippet:

    public enum Items {
        MESSAGES, CHATS, CITY_ONLINE, FRIENDS, PROFILE, SETTINGS, PEOPLE_SEARCH, CREATE_CHAT
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menuPrm) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menuPrm);
        View itemChooserLcl;
        for (int i = 0; i < menuPrm.size(); i++) {
            MenuItem itemLcl  = menuPrm.getItem(i);
                itemChooserLcl = itemLcl.getActionView();
                if (itemChooserLcl != null) {
                     //here Im marking each View' tag by enume values:
                    itemChooserLcl.setTag(Items.values()[i]);
                    itemChooserLcl.setOnClickListener(drawerMenuListener);
                }
            }
        return true;
    }
    private View.OnClickListener drawerMenuListener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Items tagLcl= (Items) v.getTag();
            switch (tagLcl){
                case MESSAGES: ;
                break;
                case CHATS : ;
                break;
                case CITY_ONLINE : ;
                break;
                case FRIENDS : ;
                break;
                case  PROFILE: ;
                break;
                case  SETTINGS: ;
                break;
                case  PEOPLE_SEARCH: ;
                break;
                case  CREATE_CHAT: ;
                break;
            }
        }
    };
    

提交回复
热议问题