包结构
整体用了策略模式,方便后续扩展转换算法,调用者不满意转换算法,也可以自己实现,灵活性较强。
package com.example.iptoint.convertStrategy;
/**
* Created by graymonkey on 18-3-14.
* 抽象转换接口,后续可能有多种转换算法
*/
public interface IIPConvertToInt {
int convertToInt(String ip);
}
package com.example.iptoint.convertStrategy;
/**
* Created by graymonkey on 18-3-14.
* 默认转换器
*/
public class DefaultConvertStrategy implements IIPConvertToInt {
@Override
public int convertToInt(String ip) {
int intIp = 0x00000000;
int shiftBits = 24;
//根据.号分割ip地址
String[] ipStrArrays = ip.split("\\.");
for (String part:ipStrArrays){
int partInt = Integer.parseInt(part);
intIp |= partInt <<shiftBits;
shiftBits -=8;
}
System.out.println(intIp);
return intIp;
}
}
package com.example.iptoint;
import com.example.iptoint.convertStrategy.DefaultConvertStrategy;
import com.example.iptoint.convertStrategy.IIPConvertToInt;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by graymonkey on 18-3-14.
* IP V4 地址抽象
*/
public class IPAddress {
private String mIpStr;
private IIPConvertToInt mDefaultConvertStrategy = new DefaultConvertStrategy();
public IPAddress(String ip) {
IPMatcher.matchIP(ip);
this.mIpStr = ip;
}
/**
* 设置IP地址转换为int的转换器
* 如果调用者不满意我们提供的算法,可以自己实现
* @param mDefaultConvertStrategy
*/
public void setConvertStrategy(IIPConvertToInt mDefaultConvertStrategy) {
this.mDefaultConvertStrategy = mDefaultConvertStrategy;
}
/**
* IP地址转换为int
* @return
*/
public int convertToInt(){
return mDefaultConvertStrategy.convertToInt(mIpStr);
}
/**抽象一个IP V4格式校验器*/
private static class IPMatcher {
static void matchIP(String ip){
//正则匹配IPV4格式
Pattern p = Pattern.compile("^((25[0-5]|2[0-4]\\d|[1]{1}\\d{1}\\d{1}|[1-9]{1}\\d{1}|\\d{1})($|(?!\\.$)\\.)){4}$");
Matcher m = p.matcher(ip);
boolean isMatch = m.matches();
if (isMatch){
System.out.println("IPv4格式正确");
} else {
throw new RuntimeException("IPv4格式错误,请检查");
}
}
}
}