接口之工厂方法的设计模式

接口用法总结

  • 接口主要用来定义规范,解除耦合关系(继承)
  • 通过接口可以指明多个类需要实现的方法,一般用于定义对象的扩张功能
  • 通过接口可以实现不相关类的相同行为,而不需要考虑这些类之间的层次关系

 工厂方法的设计模式

 1 public class Test{
 2     public static void main(String[] args){
 3     IworkFactory i = new StudentWorkFactory();
 4     i.getWork().doWork();
 5 // i.getWork() 返回一个StudengtWork() ,再.doWork
 6 
 7    IworkFactory i2 = new TeacherWorkFactory();
 8     i2.getWork().doWork();
 9 
10 
11 // 编译的时候都是接口之间在进行操作,真正运行的时候都是具体的实现类完成的事
12 }
13 
14 }
15 
16 
17 
18 
19 
20 interface IWorkFactory{
21     Work getWork();
22 
23 }
24 
25 class StudentWorkFactory implements IworkFactory{
26           public Work getWork(){
27              return new StudentWork();
28  }
29 }
30 
31 class TeacherWorkFactory implements IWOrkFactory{
32             public Work getWork(){
33             return new TeacherWork();
34 }
35 
36 }
37 
38 interface Work{
39 
40 void dowork();
41 
42 }
43 
44 class StudentWork implements Work{
45       public void dowork(){
46         System.out.println("1");
47 }
48 
49 }
50 
51 class TeacherWork implements Work{
52        public void dowork(){
53       System.out.pritln("2");
54 }
55 
56   
57 }
View Code

猜你喜欢

转载自www.cnblogs.com/aying/p/10810710.html