JAVA中设计模式

2025-11-28 07:19:11

1、观察下面程序:

定义一个接口

interface   Fruit{

    public void eat();

}

主方法实际上就相当于一个客户端;

JAVA中设计模式

2、class  Apple  implements  Fruit{

       public void eat(){

          System.out.println("吃苹果");

}

}

JAVA中设计模式

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接口,如果此时需要更换一个子类,子必须要修改主方法

JAVA中设计模式

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("吃橘子");

}

}

JAVA中设计模式

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;

}

}

JAVA中设计模式

3、public   class   interfaceDemo{

      public  static  void   main{String   args[]}{

           Fruit  f=null;定义 接口对象

           f =Factory.getInstance("apple");

           f.eat();

      }

}

程序在接口和子类之间加入一个过渡端,通过此过度端取得接口的实例化对象

一般都会称这个过度端为工厂类;

JAVA中设计模式

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢