티스토리 뷰

Java

Strategy + Command Pattern another ver.

techbard 2016.07.25 15:46

Strategy Command.zip



# Item.java


public class Item {

    private String name;

    private int id;


    public Item(String name) {

this.name = name;

    }


    public String getName() {

        return name;

    }


    public int getId() {

        return id;

    }


    public void setName(String name) {

        this.name = name;

    }


    public void setId(int id) {

        this.id = id;

    }

}



# ItemProcess.java


public interface ItemProcess<T> {

    void process(T t);

}



# ItemManager.java


import java.util.ArrayList;

import java.util.List;


public class ItemManager {

    private List<Item> items = new ArrayList<>();

    private List<ItemProcess<Item>> processes = new ArrayList<>();

    private static int id = 1;

    

    public void addItem(Item i) {

items.add(i);

    }

    

    public void addProcess(ItemProcess<Item> p) {

processes.add(p);

    }

    

    public int generateID() {

return id++;

    }

    

    public void execute() {

for (Item item : items) {

   item.setId(generateID());

   for (ItemProcess<Item> itemProcess : processes) {

itemProcess.process(item);

   }

}

    }

}



# NameProcess.java


public class NameProcess implements ItemProcess<Item> {


    @Override

    public void process(Item t) {

System.out.println("hi! " + t.getName());

    }

}



# IdProcess.java


public class IdProcess implements ItemProcess<Item> {


    @Override

    public void process(Item t) {

System.out.println("ID: " + t.getId());

    }

}



# ProcessMain.java


public class ProcessMain {


    public static void main(String[] args) {

Item item01 = new Item("x");

Item item02 = new Item("y");


ItemProcess<Item> process01 = new NameProcess();

ItemProcess<Item> process02 = new IdProcess();


ItemManager im = new ItemManager();

im.addItem(item01);

im.addItem(item02);

im.addProcess(process01);

im.addProcess(process02);


im.execute();

    }

}



# 결과


hi! x

ID: 1

hi! y

ID: 2


댓글
댓글쓰기 폼
공지사항
Total
395,135
Today
3
Yesterday
41
«   2018/11   »
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
글 보관함