fork download
  1. import java.util.HashMap;
  2. abstract class Buhin{
  3. int value;
  4. public void setValue(int value){
  5. this.value=(int)Math.round(value*1.05);
  6. }
  7. abstract void test();
  8. }
  9.  
  10. class Buhin1 extends Buhin{
  11. public void test(){
  12. System.out.println("this is buhin1");
  13. System.out.println("This value is "+value);
  14. }
  15. }
  16.  
  17. class Buhin2 extends Buhin{
  18. public void test(){
  19. System.out.println("this is buhin2");
  20. System.out.println("This value is "+value);
  21. }
  22. }
  23.  
  24. class BuhinFactory{
  25. //部品をCache
  26. private HashMap<String, Buhin> pool = new HashMap<String, Buhin>();
  27. public Buhin getBuhin(String s){
  28. Buhin b = (Buhin) pool.get(s);
  29. if(b==null){
  30. try{
  31. b=(Buhin)Class.forName(s).newInstance();
  32. pool.put(s,b);
  33. }catch(Exception e){
  34. }
  35. }
  36. return b;
  37. }
  38. }
  39.  
  40. class Main{
  41. public static void main(String[] args){
  42. BuhinFactory bf =new BuhinFactory();
  43. Buhin buhin=bf.getBuhin("Buhin2");
  44. buhin.setValue(100);
  45. buhin.test();
  46. buhin =bf.getBuhin("Buhin1");
  47. buhin.setValue(200);
  48. buhin=bf.getBuhin("Buhin2");
  49. buhin.test();
  50.  
  51. }
  52. }
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
this is buhin2
This value is 105
this is buhin2
This value is 105