java 单例模式和工厂模式实例详解
单例模式根据实例化对象时机的不同分为两种:一种是饿汉式单例,一种是懒汉式单例。
私有的构造方法
指向自己实例的私有静态引用
以自己实例为返回值的静态的公有的方法
饿汉式单例
publicclassSingleton{
privatestaticSingletonsingleton=newSingleton();
privateSingleton(){}
publicstaticSingletongetInstance(){
returnsingleton;
}
}
懒汉式单例
publicclassSingleton{
privatestaticSingletonsingleton;
privateSingleton(){}
publicstaticsynchronizedSingletongetInstance(){
if(singleton==null){
singleton=newSingleton();
}
returnsingleton;
}
}
工厂方法模式代码
interfaceIProduct{
publicvoidproductMethod();
}
classProductimplementsIProduct{
publicvoidproductMethod(){
System.out.println("产品");
}
}
interfaceIFactory{
publicIProductcreateProduct();
}
classFactoryimplementsIFactory{
publicIProductcreateProduct(){
returnnewProduct();
}
}
publicclassClient{
publicstaticvoidmain(String[]args){
IFactoryfactory=newFactory();
IProductprodect=factory.createProduct();
prodect.productMethod();
}
}
抽象工厂模式代码
interfaceIProduct1{
publicvoidshow();
}
interfaceIProduct2{
publicvoidshow();
}
classProduct1implementsIProduct1{
publicvoidshow(){
System.out.println("这是1型产品");
}
}
classProduct2implementsIProduct2{
publicvoidshow(){
System.out.println("这是2型产品");
}
}
interfaceIFactory{
publicIProduct1createProduct1();
publicIProduct2createProduct2();
}
classFactoryimplementsIFactory{
publicIProduct1createProduct1(){
returnnewProduct1();
}
publicIProduct2createProduct2(){
returnnewProduct2();
}
}
publicclassClient{
publicstaticvoidmain(String[]args){
IFactoryfactory=newFactory();
factory.createProduct1().show();
factory.createProduct2().show();
}
}
希望本文对各位朋友有所帮助
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下