码迷,mamicode.com
首页 > 其他好文 > 详细

简单工程模式

时间:2016-03-20 21:32:49      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

简单工厂模式

定义:专门定义一个类来负责创建其它类的实例,被创建的实例通常都具有共同的父类或接口;

意图:提供一个类,由它负责根据一定的条件创建某一具体类的实例;

 1 public class FactoryDemo{
 2     public static void main(String []args){
 3         IFruit fruit = Factory.getFruit("橘子");
 4         if(fruit!=null){
 5             System.out.println(fruit.get());
 6         }
 7         else{
 8             System.out.println("你要的东西不存在");
 9         }
10     }
11 }
12 
13 interface IFruit{
14     public String get();
15 }
16 
17 class Factory{
18     public static IFruit getFruit(String name){
19         if(name.equals("苹果"))
20         {
21              return new Apple();
22         }
23         else if(name.equals("橘子"))
24         {
25              return new Orange();
26         }
27         else
28         {
29             return null;
30         }
31     }
32 }
33 
34 class Apple implements IFruit{
35     public String get(){
36         return "采摘苹果";
37     }
38 }
39 
40 class Orange implements IFruit{
41     public String get(){
42         return "采摘橘子";
43     }
44 }

 

简单工程模式

标签:

原文地址:http://www.cnblogs.com/wzy330782/p/5299485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!