java 單例模式和工廠模式實例詳解
更新時間:2017年04月13日 16:33:48 作者:wuxiao5570
這篇文章主要介紹了Java設(shè)計模式編程中的單例模式和簡單工廠模式以及實例,使用設(shè)計模式編寫代碼有利于團隊協(xié)作時程序的維護,需要的朋友可以參考下
單例模式根據(jù)實例化對象時機的不同分為兩種:一種是餓漢式單例,一種是懶漢式單例。
私有的構(gòu)造方法
指向自己實例的私有靜態(tài)引用
以自己實例為返回值的靜態(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();
}
}
希望本文對各位朋友有所幫助
相關(guān)文章
springcloud項目快速開始起始模板的實現(xiàn)
本文主要介紹了springcloud項目快速開始起始模板思路的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12
利用java反射機制實現(xiàn)自動調(diào)用類的簡單方法
下面小編就為大家?guī)硪黄胘ava反射機制實現(xiàn)自動調(diào)用類的簡單方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
關(guān)于spring版本與JDK版本不兼容的問題及解決方法
這篇文章主要介紹了關(guān)于spring版本與JDK版本不兼容的問題,本文給大家?guī)砹私鉀Q方法,需要的朋友可以參考下2018-11-11
JAVA8 stream中三個參數(shù)的reduce方法對List進(jìn)行分組統(tǒng)計操作
這篇文章主要介紹了JAVA8 stream中三個參數(shù)的reduce方法對List進(jìn)行分組統(tǒng)計操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
jvm細(xì)節(jié)探索之synchronized及實現(xiàn)問題分析
這篇文章主要介紹了jvm細(xì)節(jié)探索之synchronized及實現(xiàn)問題分析,涉及synchronized的字節(jié)碼表示,JVM中鎖的優(yōu)化,對象頭的介紹等相關(guān)內(nèi)容,具有一定借鑒價值,需要的朋友可以參考下。2017-11-11

