java - Making a class more generic -


here's code i've inherited game. sample code creates armor.

at moment make new armor, need write new class. e.g.

// armor.java public class armor extends item {        public int tier;      public armor( int tier ) {         this.tier = tier;     } } 

and

// clotharmor.java     public class clotharmor extends armor {     {            name = "cloth armor";     }      public clotharmor() {         super( 1 );     }      @override     public string desc() {         return "some cloth armor.";     } } 

how structure code make more generic? seem obvious read text-based config file can see running problems when wanted create armor special abilities example.

are there resources or design patterns can use figure out how proceed?

if intent add dynamically behaviour armor, can use decorator design pattern. try have here. 1 of used pattern of gof's book, design patterns.

so, if understand needs, can read file properties want add base armor , then, using factory, add them armor using decorator pattern.

interface armor {     // put public interface of armor here     public string desc(); } class basearmor extends item implements armor {     public int tier;     public basearmor( int tier ) {         this.tier = tier;     }     public string desc() {         return "a base armor ";     } } // every new possible feature of armor has extend class abstract class armordecorator implements armor {     protected final armor armor;     // armor want decorate     public armordecorator(armor armor) {         this.armor = armor;     } } // armor made of cloth class madeofcloth extends armordecorator {     public madeofcloth(armor armor) {         super(armor);     }     @override     public string desc() {         // decoration: add feature desc method         return armor.desc() + "made of cloth ";     } } // factory reads properties file , build armors // using information read. enum armorfactory {     instance;     public armor build() {         armor armor = null;         // @ point have had read properties file         if (/* armor made of cloth */) {             armor = new madeofcloth(new basearmor(1));         }         return armor;     } } 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -