设计模式
- 工厂模式
先定义一个接口
package Interface;
public interface Shape {
void draw();
}
再定义三个实体类实现接口
//class1
package Interface;
public class CirCle implements Shape{
@Override
public void draw() {
System.out.println("圆形车");
}
}
//class2
package Interface;
public class Square implements Shape {
@Override
public void draw() {
System.out.println("正方形车");
}
}
//class3
package Interface;
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("长方形车");
}
}
创建一个工厂类,生成基于给定信息的实体类对象
package Factory;
import Interface.CirCle;
import Interface.Rectangle;
import Interface.Shape;
import Interface.Square;
public class ShapeFactory {
public Shape getshape(String shapetype){
if(shapetype == null)
{
return null;
}else if(shapetype.equalsIgnoreCase("CIRCLE") )
{
return new CirCle();
}else if(shapetype.equalsIgnoreCase("Rectangle"))
{
return new Rectangle();
}else if (shapetype.equalsIgnoreCase("SQUARE"))
{
return new Square();
}
return null;
}
}
equalsIgnoreCase方法
/**
* Compares this {@code String} to another {@code String}, ignoring case
* considerations. Two strings are considered equal ignoring case if they
* are of the same length and corresponding characters in the two strings
* are equal ignoring case.
*
* <p> Two characters {@code c1} and {@code c2} are considered the same
* ignoring case if at least one of the following is true:
* <ul>
* <li> The two characters are the same (as compared by the
* {@code ==} operator)
* <li> Applying the method {@link
* java.lang.Character#toUpperCase(char)} to each character
* produces the same result
* <li> Applying the method {@link
* java.lang.Character#toLowerCase(char)} to each character
* produces the same result
* </ul>
*
* @param anotherString
* The {@code String} to compare this {@code String} against
*
* @return {@code true} if the argument is not {@code null} and it
* represents an equivalent {@code String} ignoring case; {@code
* false} otherwise
*
* @see #equals(Object)
*/
//顺便开启读equalsIgnoreCase()方法的源码
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}
创建一个测试用例,使用“工厂类”来获取Shape对象,同时它将向工厂类传递信息以获取它所需要的类型
import Factory.ShapeFactory;
import Interface.Shape;
public class TestFactoryDemo {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape shape1 = factory.getshape("CIRCLE");
shape1.draw();
Shape shape2 = factory.getshape("RECTANGLE");
shape2.draw();
Shape shape3 = factory.getshape("SQUARE");
shape3.draw();
}
}