java 设计模式

工厂模式

   普通工厂:

    定义接口:

    public interface Gong {
      void add()throws  Exception;
      void delete()throws  Exception;
}

     实现类:

   1

    public class Gong1 implements  Gong {

    @Override
    public void add() throws Exception {
       System.out.println("添加");
        
    }

    @Override
    public void delete() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("删除");
    }

}

   2

  public class Gong2 implements  Gong {

    @Override
    public void add() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("添加2");
        
    }

    @Override
    public void delete() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("删除2");
    }
}


工厂类:

public class GongChang {
    public String type;
    public GongChang(String type){
        this.type =type;
    }
    public   Gong  test(){
        if(type=="gong1"){
            return new Gong1();
        }
        if(type=="gong2"){
            return new Gong2();
        }
        return null;
    }
}


测试类:

 public  static void main(String[]args) throws Exception{
        GongChang  gongChang = new GongChang("gong1");
        Gong ter = gongChang.test();
        ter.add();
    }


  多个工厂方法模式:

 只需要修改工厂类


public class GongChang1 {
    public  Gong  gong1(){
        return  new Gong1();
    }
    public Gong gong2(){
        return  new Gong2();
    }
}

测试类:

    //多个工厂模式
        GongChang1  gongChang1 = new GongChang1();
        Gong  gong  =gongChang1.gong1();
        gong.add();


静态工厂方法模式

  修改工厂类:

 public class GongChang2 {
    
    public static Gong  gong1(){
        return  new Gong1();
    }
    public static Gong gong2(){
        return  new Gong2();
    }

}

  测试类:

        Gong   gong  =GongChang2.gong1();
        gong.add();


       

 

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值