当前位置: 移动技术网 > IT编程>开发语言>Java > java 单例模式和工厂模式实例详解

java 单例模式和工厂模式实例详解

2019年07月22日  | 移动技术网IT编程  | 我要评论
单例模式根据实例化对象时机的不同分为两种:一种是饿汉式单例,一种是懒汉式单例。 私有的构造方法 指向自己实例的私有静态引用 以自己实例为返回值的静态的公有的方法 饿

单例模式根据实例化对象时机的不同分为两种:一种是饿汉式单例,一种是懒汉式单例

私有的构造方法

指向自己实例的私有静态引用

以自己实例为返回值的静态的公有的方法

饿汉式单例

  public class singleton {
    private static singleton singleton = new singleton();
    private singleton(){}
    public static singleton getinstance(){
      return singleton;
    }
  }

懒汉式单例

  public class singleton {
    private static singleton singleton;
    private singleton(){}
    public static synchronized singleton getinstance(){
      if(singleton==null){
        singleton = new singleton();
      }
      return singleton;
    }
  }

工厂方法模式代码

 interface iproduct {
    public void productmethod();
  }
  class product implements iproduct {
    public void productmethod() {
      system.out.println("产品");
    }
  }
  interface ifactory {
    public iproduct createproduct();
  }
  class factory implements ifactory {
    public iproduct createproduct() {
      return new product();
    }
  }
  public class client {
    public static void main(string[] args) {
      ifactory factory = new factory();
      iproduct prodect = factory.createproduct();
      prodect.productmethod();
    }
  }

抽象工厂模式代码

  interface iproduct1 {
    public void show();
  }
  interface iproduct2 {
    public void show();
  }
  class product1 implements iproduct1 {
    public void show() {
      system.out.println("这是1型产品");
    }
  }
  class product2 implements iproduct2 {
    public void show() {
      system.out.println("这是2型产品");
    }
  }
  interface ifactory {
    public iproduct1 createproduct1();
    public iproduct2 createproduct2();
  }
  class factory implements ifactory{
    public iproduct1 createproduct1() {
      return new product1();
    }
    public iproduct2 createproduct2() {
      return new product2();
    }
  }
  public class client {
    public static void main(string[] args){
      ifactory factory = new factory();
      factory.createproduct1().show();
      factory.createproduct2().show();
    }
  }

希望本文对各位朋友有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网