多语言展示
当前在线:1207今日阅读:27今日分享:41

JAVA中设计模式

工厂设计是java开发中使用的最多的一种设计模式,我来简单介绍一下!
工具/原料

Eclipse

方法/步骤
1

观察下面程序:定义一个接口interface   Fruit{    public void eat();}主方法实际上就相当于一个客户端;

2

class  Apple  implements  Fruit{       public void eat(){          System.out.println('吃苹果');}}

3

class  Orange   implements  Fruit {    public void  eat(){       System.out.println('吃橘子');}}public  class  interfaceDemo(){   public  static  void  main(String args[]){       Fruit  f=new Apple();        f.eat();}}实现Fruit接口,如果此时需要更换一个子类,子必须要修改主方法

方法/步骤2
1

工厂设计模式:interface   Fruit{    public void eat();}class  Apple  implements  Fruit{       public void eat(){          System.out.println('吃苹果');}}class  Orange   implements  Fruit {    public void  eat(){       System.out.println('吃橘子');}}

2

class  Factory{   public   static  Fruit  getInstance(String   className){        Fruit   f=null;        if(“apple”.equals(className)){           f=new  apple();        }        if('orange'.equals(className)){          f=new Orange();        }         return  f;}}

3

public   class   interfaceDemo{      public  static  void   main{String   args[]}{           Fruit  f=null;定义 接口对象           f =Factory.getInstance('apple');           f.eat();      }}程序在接口和子类之间加入一个过渡端,通过此过度端取得接口的实例化对象一般都会称这个过度端为工厂类;

推荐信息