Java-马士兵设计模式学习笔记-建造者模式

一、概述

 

二、代码

1.Animal.java

1 public interface Animal {
2     public void bark();
3 }

 

2.Dog.java

1 public class Dog implements Animal {
2 
3     @Override
4     public void bark() {
5         System.out.println("Dog wang wang !");
6     }
7 
8 }

 

3.Cat.java

1 public class Cat implements Animal {
2 
3     @Override
4     public void bark() {
5         System.out.println("cat miao miao");
6     }
7 
8 }

 

4.AnimalBuilder.java

 1 package Builder;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 public class AnimalBuilder {
 7 
 8     private static List<Animal> animals = new ArrayList<Animal>();
 9     
10     public static List<Animal> getDogs(int count){
11         for(int i = 0; i<count ;i++){
12             animals.add(new Dog());
13         }
14         return animals;
15     }
16     
17     public static List<Animal> getCat(int count){
18         for(int i = 0; i<count ;i++){
19             animals.add(new Cat());
20         }
21         return animals;
22     }
23 }

 

5.AnimalFactoryTest.java

 1 package Builder;
 2 
 3 import java.util.List;
 4 
 5 import org.junit.Test;
 6 
 7 public class AnimalFactoryTest {
 8 
 9     @Test
10     public void test() {
11         List<Animal> animals = AnimalBuilder.getDogs(3);
12         for(int i = 0; i<animals.size() ;i++){
13             animals.get(i).bark();
14         }
15     }
16 
17 }

 

 

三、运行结果

posted @ 2015-06-22 22:52  shamgod  阅读(680)  评论(0编辑  收藏  举报
haha