我正在查看 Google I/O Android App iosched链接,发现他们在 helper/util 类中主要使用静态方法。但是,我发现很多人不推荐在辅助类中使用静态方法。
假设我有 3 个活动正在执行一些工作,例如显示警报对话框或通知,那么我需要在所有 3 个活动中添加相同的代码。如果我正在编写来自 10 个不同活动的文件怎么办。使用带有静态方法的辅助类不是比一遍又一遍地编写相同代码更好的方法吗?如果不是,那么最好的方法是什么。
public class NotificationHelper {
/**
* create notification
* @param context activity context
* @param title notification title
* @param contentText notification text
* @param mNotificationId notification id
*/
public static void setUpNotification(Context context, String title, String contentText, int mNotificationId) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context).setLargeIcon((BitmapFactory.decodeResource(context.getResources(),R.drawable.launcher)))
.setSmallIcon(R.drawable.ic_notif)
.setContentTitle(title)
.setContentText(contentText).setPriority(NotificationCompat.PRIORITY_MAX);
Intent resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setOngoing(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mNotificationId, mBuilder.build());
}
/**
* cancel notification
* @param ctx context
* @param notifyId id of notification to be cancelled
*/
public static void cancelNotification(Context ctx, int notifyId) {
NotificationManager nMgr = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancel(notifyId);
}
}
Run Code Online (Sandbox Code Playgroud)
的使用Helper classes在面向对象编程中几乎没有争议。您可以使用普通类并包含类的对象。或者您可以将公共代码放在基类中,然后对其进行扩展。但是,如果我们决定使用 Helper 类,那么以下几点可以帮助您作为指导。
助手类是实用程序实体。它们最好像实用程序一样使用,因此通过将默认构造函数标记为私有来防止实例化和扩展。
公开“静态”方法。看看这些方法是否只是作为实用程序类的包中的类需要,然后将访问修饰符保留为包私有,如果外部类也需要这些方法,那么您可以将它们设为公开。目的是防止公共 API 过多地暴露包详细信息。您还可以尝试在参数和返回类型中进行抽象。
尝试stateless通过没有字段来保留此类类。即使不需要,保持(静态)字段也可能导致引用对象。
正确命名这些类,让帮助类的用户知道它的意图,并且它们只是实用程序类。还要根据用途命名方法并尽量减少混淆。