设计模式:
解决某类问题的一个固定的编程模式,思路 23种
1.单例模式:只有一个实例
//这个类的只给提供一个实例
public class SessionFactory {
//1.声明一个私有的静态的本类的属性
private static SessionFactory sf;
//2.构造 方法私有化
private SessionFactory() {
}
//3.提供一个静态方法,返回私有的静态的本类的属性
//向外界提供一个实例
public static SessionFactory getIntance(){
if(sf==null){
sf = new SessionFactory();
}
return sf;
}
}
测试
public class SessionFactoryTest {
@Test
public void test() {
SessionFactory sf = SessionFactory.getIntance();
SessionFactory sf1 = SessionFactory.getIntance();
System.out.println(sf==sf1);
}
}
2.工厂模式:一般对象都是通过new构造方法来创建的,工厂模式是提供了一种方法,可以通过这个方法来获取对象
public class AccountFactory {
//Account工厂
public static Account openAccount(int type,String ename, String password, String email,
String personId, double balance){
if(type==0){
return new SavingAccount(ename, password, email, personId, balance);
}else if(type==1){
return new CreditAccount(ename, password, email, personId, balance, 10000);
}
return null;
}
}
内部类
什么是内部类,定义在类的内部的类叫内部类
分类:
以类成员的形式定义:成员内部类
有无static修饰
有:静态内部类
无:动态内部类
定义在方法的内部:局部内部类,匿名内部类
Jdk1.8之前的匿名内部类只能访问被final修饰的局部变量
public class Outer {
private int a=5;//成员属性
public void m1(){
System.out.println("a"+a);
// System.out.println("ia"+ia);//内部类可以直接访问外部类的成员,外部类不能直接访问内部类的成员
Inner1 inner1 = new Inner1();
System.out.println("id"+inner1.a);
}
//成员内部类
public class Inner1{
private int a = 10;//覆盖外部类的a属性
public void m1(){
System.out.println("访问外部类的私有属性a"+Outer.this.a);
//如果内部类没有覆盖a,可以直接访问外部类的a
Outer.this.m1();//Outer.this表示外部类的当前对象
}
public void m2(){
Inner2 i2 = new Inner2();
i2.m1();
}
}
public static class Inner2{
public void m1(){
// System.out.println(a);//静态成员不能访问动态成员
System.out.println("静态成员不能访问动态成员");
}
}
public void m3(){
//定义在方法的内容的类叫局部内部类,局部内部类只在方法内可见
class Inner4 {
public void m1(){
}
}
Inner4 i4 = new Inner4();
i4.m1();
}
public void m4(){
int b = 10;
//匿名内部类,通常用于创建某一个接口或类的子类,且只需要使用一次
Account a = new Account() {
@Override
public void withdraw(double save) {
// System.out.println(b);//jdk1.8之前匿名内部类只能访问被final修饰的局部变量
}
};
}
}
测试
mport org.junit.Test;
public class OuterTest {
@Test
public void test() {
Outer outer = new Outer();
outer.m1();//访问外部类的m1方法
//a5 id10
}
@Test
public void test2() {
Outer outer = new Outer();
// outer.m1();
//访问内部类m1方法
Outer.Inner1 in = outer.new Inner1();//创建动态内部类对象:new Outer().new Inner();
in.m1();
//访问外部类的私有属性a5
//a5
//id10
}
@Test
public void test3() {
Outer outer = new Outer();
// outer.m1();
//访问静态内部类m1方法
Outer.Inner2 in = new Outer.Inner2();//创建静态内部类对象:new Outer.StaticInner();
in.m1();
}
}
为什么要使用内部类:
内部类可以直接使用外部类的私有属性
访问规则
静态内部类只能访问静态成员
成员内部类可以类的外部访问
静态内部类new Outer.StaticInner()
动态内部类:new Outer().new Inner()
局部内部类只能在方法的内部访问
当内部类被编译后,其生成的class文件名为:外部类名$内部类名.class