static 静态代码块 动态代码块 单例

时间:2023-03-08 17:55:39
static 静态代码块 动态代码块 单例

1. 共享,不属于对象,属于类,类成员变量,任何一个类的对象都有该属性,一旦被修改,则其他对象中的该属性也被更改。

2. 类中方法是static的,可以通过类名直接访问,不用new一个该类的对象。

3. 唯一,无论有多少类的对象,static属性在内存中只有一份。用于实现单例模式,连接池等问题。

简单单例模式

package weiguoyuan.chainunicom.cn;

class Single{
private static Single only = new Single();//private 封装 以免外界操作 static 只有一个
private Single(){}//外界不可以new 来访问构造函数
public static Single getOnly(){//public 外界访问口 static 才能由外界通过类名直接访问
return only;
}
}
public class TestSingle { public static void main(String[] args) {
Single s1 = Single.getOnly();
Single s2 = Single.getOnly();
System.out.println(s1==s2);
}
}

下面代码是为了获得jedis连接只操作一次的单例模式。

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig; import com.wandoulabs.jodis.JedisResourcePool;
import com.wandoulabs.jodis.RoundRobinJedisPool; public class GetJedis{
private static JedisResourcePool jedisPool = new RoundRobinJedisPool("192.168.253.128:2181",
30000, "/zk/codis/db_test/proxy", new JedisPoolConfig());
public static Jedis getJedis(){
return jedisPool.getResource();
}
}
   //获得jedis连接
Jedis jedis = GetJedis.getJedis();

4. 静态代码块只在类加载的时候执行一次,一般用于初始化,和new出的对象个数无关。静态代码块中可以new该类的对象,可以用该对象访问类中非静态的方法属性。

5. 动态代码块可以理解为多个构造函数形同的部分,把这部分提取出来,有new操作,动态代码块就会执行一次,没有对象生成不执行。

package weiguoyuan.chainunicom.cn;

public class TestStatic {
static {
System.out.println("TestStatic static code1");
}
public TestStatic(){
}
public TestStatic(int i){
System.out.println("TestStatic Constructor");
}
{
System.out.println("TestStatic dynamic code");
}
static {
System.out.println("TestStatic static code2");
} }
class Test {
static {
System.out.println("Test static code1");
}
{
System.out.println("Test dynamic code");
}
public static void main(String[] args){
new TestStatic();
new TestStatic();
}
static {
System.out.println("Test static code2");
}
}

执行结果:

Test static code1
Test static code2
TestStatic static code1
TestStatic static code2
TestStatic dynamic code
TestStatic Constructor
TestStatic dynamic code
TestStatic Constructor

代码块先于构造方法执行