One aspect of cadence that hasn't been mentioned is that, ideally, the point of your gears is to allow you to maintain your optimal cadence and force on the pedals, while only varying your ground speed. If you had a ideal bicycle with an infinite number of gears, your pedaling cadence and force would be completely independent of uphills, flats, and downhills — you would simply go faster or slower based on conditions.
Obviously, you don't have an ideal bicycle, but the number of gears on modern bikes is more than enough to closely approximate it. So find a cadence that works for you and try to stay as close to it as possible. Eventually it will become second nature. You will spin faster in a sprint to increase your peak power, or slower to recover after the sprint, but outside of those, keep it constant.
Generally speaking, your optimal cadence will be where the load on both your anaerobic (strength/muscle) and aerobic (endurance/cardiovascular) systems are sustainable. At the constant power output, keeping your RPMs too low will tire your muscles, but ramping them up too high will exceed the capacity of your heart to keep up. However, it's much easier to increase your cardiovascular endurance than to increase your muscular endurance; that's what your heart excels at in the first place. So pushing your RPMs higher will (to a point), strengthen your heart and allow you to maintain a higher power output for longer periods of time.