2019年5月13日 星期一

7天學會設計模式 CHAP04 工廠模式 Factory

7天學會設計模式
http://www.books.com.tw/products/0010750585

chap04.
工廠模式 Factory
目的:提供一個工廠介面,將產生實體的程式碼交由子類別各自實現。
package com.ssc24.chap04.demo01;
public interface Adventurer {
 public String getType();
}

package com.ssc24.chap04.demo01;
public class Archer implements Adventurer {
 @Override
 public String getType() {
  System.out.println("我是弓箭手");
  return this.getClass().getSimpleName();
 }
}

package com.ssc24.chap04.demo01;
public class Warrior implements Adventurer {
 @Override
 public String getType() {
  System.out.println("我是戰士");
  return this.getClass().getSimpleName();
 }
}

package com.ssc24.chap04.demo01;
public interface ITrainingCamp {
 public Adventurer trainAdventurer();
}

package com.ssc24.chap04.demo01;
public class ArcherTrainingCamp implements ITrainingCamp {
 @Override
 public Adventurer trainAdventurer() {
  System.out.println("產生一個弓箭手");
  return new Archer();
 }
}

package com.ssc24.chap04.demo01;
public class WarriorTrainingCamp implements ITrainingCamp {
 @Override
 public Adventurer trainAdventurer() {
  System.out.println("產生一個戰士");
  return new Warrior();
 }
}

package com.ssc24.chap04.demo01;
import static org.junit.Assert.*;
import org.junit.Test;
import junit.framework.Assert;
public class TrainingCampTest {
 @Test
 public void test() {
  System.out.println("=========== 工廠模式測試 ===========");
  ITrainingCamp trainCamp = new ArcherTrainingCamp();
  Adventurer memberA = trainCamp.trainAdventurer();
  Assert.assertEquals(memberA.getType(), "Archer");
  trainCamp = new WarriorTrainingCamp();
  Adventurer memberB = trainCamp.trainAdventurer();
  Assert.assertEquals(memberB.getType(), "Warrior");
 }
}

/**
=========== 工廠模式測試 ===========
產生一個弓箭手
我是弓箭手
產生一個戰士
我是戰士
**/