java 單例模式和工廠模式實(shí)例詳解
單例模式根據(jù)實(shí)例化對(duì)象時(shí)機(jī)的不同分為兩種:一種是餓漢式單例,一種是懶漢式單例。
私有的構(gòu)造方法
指向自己實(shí)例的私有靜態(tài)引用
以自己實(shí)例為返回值的靜態(tài)的公有的方法
餓漢式單例
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("產(chǎn)品");
}
}
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型產(chǎn)品");
}
}
class Product2 implements IProduct2 {
public void show() {
System.out.println("這是2型產(chǎn)品");
}
}
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();
}
}
希望本文對(duì)各位朋友有所幫助
相關(guān)文章
springcloud項(xiàng)目快速開始起始模板的實(shí)現(xiàn)
本文主要介紹了springcloud項(xiàng)目快速開始起始模板思路的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12
SWT(JFace)體驗(yàn)之圖片的動(dòng)態(tài)漸變效果
SWT(JFace)體驗(yàn)之圖片的動(dòng)態(tài)漸變效果2009-06-06
利用java反射機(jī)制實(shí)現(xiàn)自動(dòng)調(diào)用類的簡單方法
下面小編就為大家?guī)硪黄胘ava反射機(jī)制實(shí)現(xiàn)自動(dòng)調(diào)用類的簡單方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-08-08
關(guān)于spring版本與JDK版本不兼容的問題及解決方法
這篇文章主要介紹了關(guān)于spring版本與JDK版本不兼容的問題,本文給大家?guī)砹私鉀Q方法,需要的朋友可以參考下2018-11-11
JAVA8 stream中三個(gè)參數(shù)的reduce方法對(duì)List進(jìn)行分組統(tǒng)計(jì)操作
這篇文章主要介紹了JAVA8 stream中三個(gè)參數(shù)的reduce方法對(duì)List進(jìn)行分組統(tǒng)計(jì)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08
jvm細(xì)節(jié)探索之synchronized及實(shí)現(xiàn)問題分析
這篇文章主要介紹了jvm細(xì)節(jié)探索之synchronized及實(shí)現(xiàn)問題分析,涉及synchronized的字節(jié)碼表示,JVM中鎖的優(yōu)化,對(duì)象頭的介紹等相關(guān)內(nèi)容,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-11-11

