首页 > 编程语言 > 详细

Java学习---常见的模式

时间:2018-07-18 23:04:11      阅读:228      评论:0      收藏:0      [点我收藏+]

Java的常见模式

适配器模式

技术分享图片
 1 package com.huawei;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 import java.util.Observable;
 8 import java.util.Observer;
 9 
10 interface Window
11 {
12     public  void open();
13     public  void close();
14     public  void active();
15 }
16 
17 abstract class WindowAdapter implements Window
18 {
19     public  void open(){}
20     public  void close(){}
21     public  void active(){}
22 }
23 
24 class WindowImpl extends WindowAdapter
25 {
26     public  void open()
27     {
28         System.out.println("Open.......");
29     }
30     public  void close()
31     {
32         System.out.println("Close.......");
33     }
34     public  void active()
35     {
36         System.out.println("Active.......");
37     }
38 }
39 
40 
41 public class ForNumber
42 {
43     public static void main(String args[])
44     {
45        Window win = new WindowImpl();
46        win.open();
47        win.close();
48     }
49 }
View Code

工厂模式

技术分享图片
 1 package com.huawei;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 import java.util.Observable;
 8 import java.util.Observer;
 9 
10 interface Fruit
11 {
12     public void eat();
13 }
14 
15 class Apple implements Fruit
16 {
17 
18     public void eat()
19     {
20         System.out.println("Eat Apple");
21     }
22     
23 }
24 
25 
26 class Orange implements Fruit
27 {
28     public void eat()
29     {
30         System.out.println("Eat Orange");
31     }
32 }
33 //定义工厂
34 class Factory
35 {
36     public static Fruit getInstance(String className)
37     {   
38         Fruit f = null;
39         if ("apple".equals(className))
40         {
41             f = new Apple();  
42         }
43         
44         if ("orange".equals(className))
45         {
46             f = new Orange();  
47         }
48         
49         return f;
50     }
51 }
52 
53 public class ForNumber
54 {
55     public static void main(String args[])
56     {
57        Fruit f = null;                      //定义接口对象
58        f = new Factory().getInstance("apple");
59        f.eat();
60     }
61 }
View Code

 

Java学习---常见的模式

原文:https://www.cnblogs.com/ftl1012/p/javamodel.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!